React中常见的TypeScript定义使用

318 阅读1分钟

在我学习typescript时,想在react中使用typescript写代码,从头开始的时候是懵逼的,因为官方文档并没有使用typescript的教程,多是自己在网上查,自己看定义摸索

所以今天把我用过的,总结归纳一下,希望能帮助到同样在摸索的同学

以下代码react版本为17x,在UmiJS官方typescript模版中无报错

image.png

类型简述

一些React的内置类型

  • React.ReactElement —— 使用React.createElement创建的,可以简单理解为React中的JSX的元素
  • React.ReactNode —— <div>xxx</div> xxx的合法类型
  • React.CSSProperties —— 组件内联的style对象的类型
  • React.RefObject —— React.createRef创建的类型,只读不可改
  • React.MutableRefObject —— useRef创建的类型,可以修改
  • ...

组件声明

组件声明分为类组件和函数组件

类组件

类组件使用的定义主要为React.Component<P,S>React.PureComponent<P,S,SS>

// 自定义样式
const divStyle: React.CSSProperties = {
  padding: '0 30px',
  textAlign: 'left',
};
interface AppProps {
  value: string;
}
interface AppState {
  count: number;
}
class Index extends React.Component<AppProps, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
        count: 0
    };
  }

  render() {
    return (
      <div className={styles.div} style={divStyle}>
        <div>关于我们</div>
      </div>
    );
  }
}

export default Index;

React.Component<P,S>这里的Pprops的类型,Sstate的类型,可以写为React.Component<AppProp>,因为state的类型会自己推断(建议写全,否则可能会报错)

在上面PureComponent中还有个SS,这个SSgetSnapshotBeforeUpdate的返回值,这个暂时没用到,有需要的可自行研究一下。