React TypeScript 开发实践

一、基础知识

React is a JavaScript library for building user interfaces.
It is maintained by Facebook and a community of individual developers and companies.
React allows developers to create reusable UI components and is widely used in web and mobile app development.
TypeScript is a programming language that is a superset of JavaScript and adds static typing, interfaces, and other features to the language.
TypeScript enhances the development experience in React by providing type checking and improving code readability and maintainability.
With TypeScript, it is easier to catch errors during development and refactor code as projects grow in complexity.

在安装 TypeScript 时,可以选择直接使用 create-react-app 脚手架。在使用 create-react-app 时加上 –template typescript 参数即可:

npx create-react-app my-app --template typescript

二、函数组件

React 中的函数组件是一种无状态的组件,可以通过函数输入来返回 JSX 元素。
在 TypeScript 中,函数组件需要使用泛型来定义输入的类型和返回值的类型。


interface Props {
  name: string;
}

const Greeting: React.FC = ({name}) => (
  <div>Hello {name}</div>
);

在函数组件中,React 提供了一些 hooks 来实现组件状态管理和生命周期管理。
在 TypeScript 中,需要根据 hooks 的类型来定义与 hooks 相关的变量和参数类型。


import React, { useState, useEffect } from 'react';

interface Props {
  name: string;
}

const Greeting: React.FC = ({name}) => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <div>Hello {name}! You clicked {count} times.</div>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

三、类组件

React 中类组件继承自 React.Component 类,可以使用类属性和生命周期方法来管理组件状态和生命周期。
在 TypeScript 中,需要定义 Props 和 State 接口来规范输入和状态的类型。


interface Props {
  name: string;
}

interface State {
  count: number;
}

class Greeting extends React.Component {
  constructor(props: Props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <div>Hello {this.props.name}! You clicked {this.state.count} times.</div>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

四、组件通信

在 React 中,组件间的通信可以通过 props 和 Context API 来实现。
在 TypeScript 中,需要定义接口来规范 props 和 context 的类型。


interface AppProps {
  title: string;
}

const App: React.FC<AppProps> = ({title}) => (
  <div>
    <Header title={title} />
    <Main />
  </div>
);

interface HeaderProps {
  title: string;
  subtitle?: string;
}

const Header: React.FC<HeaderProps> = ({title, subtitle}) => (
  <div>
    <h1>{title}</h1>
    {subtitle && <h2>{subtitle}</h2>}
  </div>
);

interface ThemeContextProps {
  theme: 'light' | 'dark';
}

const ThemeContext = React.createContext<ThemeContextProps>({
  theme: 'light',
});

const Main: React.FC = () => (
  <div>
    <ThemeContext.Provider value={{ theme: 'light' }}>
      <Content />
    </ThemeContext.Provider>
  </div>
);

const Content: React.FC = () => {
  const { theme } = React.useContext(ThemeContext);
  return (
    <div style={{ backgroundColor: theme === 'light' ? 'white' : 'black', color: theme === 'light' ? 'black' : 'white' }}>
      <p>This is the main content.</p>
    </div>
  );
};

五、组件库

在 React 中,组件库可以帮助开发者快速搭建项目 UI。
Ant Design 是一个流行的开源组件库,提供了丰富的 UI 组件和可配置的样式主题,适用于 Web 和移动端项目。
在 TypeScript 中,Ant Design 提供了 Typed API 来提供完整的类型推断和代码提示。


import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'antd';

ReactDOM.render(<Button type="primary">Click me!</Button>, document.getElementById('root'));

六、总结

React TypeScript 是一种支持静态类型检查的开发方式,可以提高项目的可维护性和开发效率。
在 React TypeScript 开发中,可以使用函数组件和类组件来实现组件状态和生命周期管理,使用 props 和 Context API 来实现组件通信,使用组件库来快速搭建项目 UI。
使用 TypeScript 可以更好地规范和管理代码,减少代码错误和维护成本。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/291249.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-24 13:14
下一篇 2024-12-24 13:14

相关推荐

  • @uiw/react-amap介绍

    本文将详细阐述@uiw/react-amap的使用方法和参数配置,以及如何在React应用中集成高德地图组件。 一、@uiw/react-amap简介 @uiw/react-ama…

    编程 2025-04-29
  • Webrtc音视频开发React+Flutter+Go实战PDF

    本文将从多个方面介绍如何使用React、Flutter和Go来进行Webrtc音视频开发,并提供相应的代码示例。 一、Webrtc音视频开发介绍 Webrtc是Google开发的一…

    编程 2025-04-27
  • React简书项目

    本文将从以下几个方面介绍React简书项目: 项目概述 组件分析 路由配置 Redux状态管理 项目优化 一、项目概述 React简书项目是一个类似于博客的Web应用,提供用户撰写…

    编程 2025-04-27
  • React-Icons:强大的图标库

    一、React-Icons的介绍 React-Icons 是一个可重用的 React 组件集合,构建了一组常见的图标,可用于任何 React.js 项目。它为所有的图标提供了友好的…

    编程 2025-04-25
  • TypeScript declare详解

    一、declare语句的作用 1、文字阐述内容:TypeScript中的declare语句是用来定义变量、函数、类等外部代码块的类型。它告诉TypeScript编译器某个变量实际上…

    编程 2025-04-25
  • TypeScript中的foreach循环

    一、概述 JavaSript是一门灵活的语言,其中的数组也同样灵活多变。这就使得在一个数组上执行某些操作变得很方便。其中,forEach()就是用来遍历数组的。 在TypeScri…

    编程 2025-04-24
  • React 子组件调用父组件方法

    一、基本介绍 React 是一个非常流行的 JavaScript 库,用于构建用户界面。React 的主要思想是组件化,允许将 UI 拆分为独立的、可复用的部分。React 组件有…

    编程 2025-04-23
  • useMemo——提高React性能的利器

    一、什么是useMemo React中提供了一种优化组件性能的钩子函数——useMemo。它可以帮助我们避免在每次渲染时都执行的昂贵计算。 useMemo钩子函数接收两个参数:计算…

    编程 2025-04-23
  • Flutter和React Native的比较

    一、性能比较 Flutter是Google推出的移动端UI框架,最初是为了高性能而设计的。它使用Dart编写,具有JIT和AOT两种编译模式,可以更好地优化性能。相比之下,Reac…

    编程 2025-04-23
  • React Context 实现原理详解

    一、Context是什么? Context是React提供的一种跨组件层级共享数据的方式。它解决了React组件之间数据传递的诸多问题。 1.1 基本用法 const ThemeC…

    编程 2025-04-23

发表回复

登录后才能评论