【React+Typescript】React.FC与React.Component使用和区别

13,434 阅读1分钟

Typescript中,React 的组件可以定义为 函数(React.FC<>)或class(继承React.Component) 的形式。

React.FC(函数组件)

React.FC是函数式组件,是在TypeScript使用的一个泛型。FC是FunctionComponent的缩写,React.FC可以写成React.FunctionComponent

函数组件是一个纯函数,使用React.FC来写 React 组件的时候,不能用setState,取而代之的是useState()useEffect等 Hook API。函数组件也称为无状态组件。

React.FC 包含了 PropsWithChildren 的泛型,不用显式的声明 props.children 的类型。React.FC<> 对于返回类型是显式的,而普通函数版本是隐式的(否则需要附加注释)。

React.FC提供了类型检查和自动完成的静态属性:displayName,propTypes和defaultProps(注意:defaultProps与React.FC结合使用会存在一些问题)。

import React, { useState } from 'react';

interface IProps {
    test?: any;
}
const Index: React.FC<IProps> = (props) => {
    let [count, setCount] = useState(0);
    return(
        <div>
            <p>{count}</p>
            <button onClick={() => setCount(count + 1)}>Click</button>
        </div>
    );
};
export default Index;

React.Component(类组件)

React.Component为es6形式,取代了es5原生方式定义的组件React.createClass

定义 class 组件,需要继承 React.ComponentReact.Component是类组件,在TypeScript中,React.Component是通用类型(aka React.Component<PropType, StateType>),要为其提供(可选)propsstate类型参数。

import React, {Component} from 'react';

interface IProps {
    message1?:any
}
interface IState {
    message2:any
}

class Index extends Component<IProps,IState> {
    //构造函数
    constructor(props: IProps, context: any) {
        super(props, context);
        this.state={
            message2:"test"
        }
    }
    render() {
        return (
            <div>
                <div>{this.state.message2}</div>
                <div>{this.props.message1}</div>
            </div>
        );
    }
}
export default Index;

函数组件和类组件的区别

两者最明显的不同就是在语法上,函数组件是一个纯函数,它接收一个props对象返回一个react元素。而类组件需要去继承React.Component并且创建render函数返回react元素,这将会要更多的代码,虽然它们实现的效果相同。

类组件使用的时候要实例化,而函数组件直接执行函数取返回结果即可。

函数组件不能访问this对象,无法访问生命周期的方法,没有状态state

类组件有this,有生命周期,有状态state

无状态(函数)组件只能访问输入的props,同样的props会得到同样的渲染结果,不会有副作用。

函数组件的性能比类组件的性能要高,不知道用什么组件类型时,推荐用React.FC