ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

react 中使用 TypeScript 的几点总结

2020-05-22 10:54:42  阅读:515  来源: 互联网

标签:TypeScript 高阶 Component react state 组件 几点 声明 class


https://blog.csdn.net/sinat_17775997/article/details/84203095 大佬文章,留着备用。

写在最前面

  • 为了在 react 中更好的使用 ts,进行一下讨论
  • 怎么合理的再 react 中使用 ts 的一些特性让代码更加健壮

讨论几个问题,react 组件的声明?react 高阶组件的声明和使用?class组件中 props 和 state 的使用?...

在 react 中使用 ts 的几点原则和变化

  • 所有用到jsx语法的文件都需要以tsx后缀命名
  • 使用组件声明时的Component<P, S>泛型参数声明,来代替PropTypes!
  • 全局变量或者自定义的window对象属性,统一在项目根下的global.d.ts中进行声明定义
  • 对于项目中常用到的接口数据对象,在types/目录下定义好其结构化类型声明

声明React组件

  • react中的组件从定义方式上来说,分为类组件和函数式组件。

  • 类组件的声明

  1.   class App extends Component<IProps, IState> {
  2.   static defaultProps = {
  3.   // ...
  4.   }
  5.    
  6.   readonly state = {
  7.   // ...
  8.   };
  9.   // 小技巧:如果state很复杂不想一个个都初始化,可以结合类型断言初始化state为空对象或者只包含少数必须的值的对象: readonly state = {} as IState;
  10.   }
  11.   复制代码

需要特别强调的是,如果用到了state,除了在声明组件时通过泛型参数传递其state结构,还需要在初始化state时声明为 readonly

这是因为我们使用 class properties 语法对state做初始化时,会覆盖掉Component<P, S>中对statereadonly标识。

函数式组件的声明

  1.   // SFC: stateless function components
  2.   // v16.7起,由于hooks的加入,函数式组件也可以使用state,所以这个命名不准确。新的react声明文件里,也定义了React.FC类型^_^
  3.   const List: React.SFC<IProps> = props => null
  4.   复制代码

class组件都要指明props和state类型吗?

  • 是的。只要在组件内部使用了propsstate,就需要在声明组件时指明其类型。
  • 但是,你可能发现了,只要我们初始化了state,貌似即使没有声明state的类型,也可以正常调用以及setState。没错,实际情况确实是这样的,但是这样子做其实是让组件丢失了对state的访问和类型检查!
  1.   // bad one
  2.   class App extends Component {
  3.   state = {
  4.   a: 1,
  5.   b: 2
  6.   }
  7.    
  8.   componentDidMount() {
  9.   this.state.a // ok: 1
  10.    
  11.   // 假如通过setState设置并不存在的c,TS无法检查到。
  12.   this.setState({
  13.   c: 3
  14.   });
  15.    
  16.   this.setState(true); // ???
  17.   }
  18.   // ...
  19.   }
  20.    
  21.   // React Component
  22.   class Component<P, S> {
  23.   constructor(props: Readonly<P>);
  24.   setState<K extends keyof S>(
  25.   state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
  26.   callback?: () => void
  27.   ): void;
  28.   forceUpdate(callBack?: () => void): void;
  29.   render(): ReactNode;
  30.   readonly props: Readonly<{ children?: ReactNode }> & Readonly<P>;
  31.   state: Readonly<S>;
  32.   context: any;
  33.   refs: {
  34.   [key: string]: ReactInstance
  35.   };
  36.   }
  37.    
  38.    
  39.   // interface IState{
  40.   // a: number,
  41.   // b: number
  42.   // }
  43.    
  44.   // good one
  45.   class App extends Component<{}, { a: number, b: number }> {
  46.    
  47.   readonly state = {
  48.   a: 1,
  49.   b: 2
  50.   }
  51.    
  52.   //readonly state = {} as IState,断言全部为一个值
  53.    
  54.   componentDidMount() {
  55.   this.state.a // ok: 1
  56.    
  57.   //正确的使用了 ts 泛型指示了 state 以后就会有正确的提示
  58.   // error: '{ c: number }' is not assignable to parameter of type '{ a: number, b: number }'
  59.   this.setState({
  60.   c: 3
  61.   });
  62.   }
  63.   // ...
  64.   }
  65.   复制代码

使用react高阶组件

什么是 react 高阶组件?装饰器?

  • 因为react中的高阶组件本质上是个高阶函数的调用,所以高阶组件的使用,我们既可以使用函数式方法调用,也可以使用装饰器。但是在TS中,编译器会对装饰器作用的值做签名一致性检查,而我们在高阶组件中一般都会返回新的组件,并且对被作用的组件的props进行修改(添加、删除)等。这些会导致签名一致性校验失败,TS会给出错误提示。这带来两个问题:

第一,是否还能使用装饰器语法调用高阶组件?

  • 这个答案也得分情况:如果这个高阶组件正确声明了其函数签名,那么应该使用函数式调用,比如 withRouter
  1.   import { RouteComponentProps } from 'react-router-dom';
  2.    
  3.   const App = withRouter(class extends Component<RouteComponentProps> {
  4.   // ...
  5.   });
  6.    
  7.   // 以下调用是ok的
  8.   <App />
  9.   复制代码

如上的例子,我们在声明组件时,注解了组件的props是路由的RouteComponentProps结构类型,但是我们在调用App组件时,并不需要给其传递RouteComponentProps里说具有的locationhistory等值,这是因为withRouter这个函数自身对齐做了正确的类型声明。

第二,使用装饰器语法或者没有函数类型签名的高阶组件怎么办?


如何正确的声明高阶组件?

  • 就是将高阶组件注入的属性都声明可选(通过Partial这个映射类型),或者将其声明到额外的injected组件实例属性上。 我们先看一个常见的组件声明:
  1.   import { RouteComponentProps } from 'react-router-dom';
  2.    
  3.   // 方法一
  4.   @withRouter
  5.   class App extends Component<Partial<RouteComponentProps>> {
  6.   public componentDidMount() {
  7.   // 这里就需要使用非空类型断言了
  8.   this.props.history!.push('/');
  9.   }
  10.   // ...
  11.   });
  12.    
  13.   // 方法二
  14.   @withRouter
  15.   class App extends Component<{}> {
  16.   get injected() {
  17.   return this.props as RouteComponentProps
  18.   }
  19.    
  20.   public componentDidMount() {
  21.   this.injected.history.push('/');
  22.   }
  23.   // ...
  24.   复制代码

如何正确的声明高阶组件?

  1.   interface IUserCardProps {
  2.   name: string;
  3.   avatar: string;
  4.   bio: string;
  5.    
  6.   isAdmin?: boolean;
  7.   }
  8.   class UserCard extends Component<IUserCardProps> { /* ... */}
  9.   复制代码

上面的组件要求了三个必传属性参数:name、avatar、bio,isAdmin是可选的。加入此时我们想要声明一个高阶组件,用来给UserCard传递一个额外的布尔值属性visible,我们也需要在UserCard中使用这个值,那么我们就需要在其props的类型里添加这个值:

  1.   interface IUserCardProps {
  2.   name: string;
  3.   avatar: string;
  4.   bio: string;
  5.   visible: boolean;
  6.    
  7.   isAdmin?: boolean;
  8.   }
  9.   @withVisible
  10.   class UserCard extends Component<IUserCardProps> {
  11.   render() {
  12.   // 因为我们用到visible了,所以必须在IUserCardProps里声明出该属性
  13.   return <div className={this.props.visible ? '' : 'none'}>...</div>
  14.   }
  15.   }
  16.    
  17.   function withVisiable(WrappedComponent) {
  18.   return class extends Component {
  19.   render() {
  20.   return <WrappedComponent {..this.props} visiable={true} />
  21.   }
  22.   }
  23.   }
  24.   复制代码
  • 但是这样一来,我们在调用UserCard时就会出现问题,因为visible这个属性被标记为了必需,所以TS会给出错误。这个属性是由高阶组件注入的,所以我们肯定是不能要求都再传一下的。

可能你此时想到了,把visible声明为可选。没错,这个确实就解决了调用组件时visible必传的问题。这确实是个解决问题的办法。但是就像上一个问题里提到的,这种应对办法应该是对付哪些没有类型声明或者声明不正确的高阶组件的。

所以这个就要求我们能正确的声明高阶组件:

  1.   interface IVisible {
  2.   visible: boolean;
  3.   }
  4.    
  5.   //排除 IVisible
  6.   function withVisible<Self>(WrappedComponent: React.ComponentType<Self & IVisible>): React.ComponentType<Omit<Self, 'visible'>> {
  7.   return class extends Component<Self> {
  8.   render() {
  9.   return <WrappedComponent {...this.props} visible={true} />
  10.   }
  11.   }
  12.   }
  13.   复制代码

如上,我们声明withVisible这个高阶组件时,利用泛型和类型推导,我们对高阶组件返回的新的组件以及接收的参数组件的props都做出类型声明。

标签:TypeScript,高阶,Component,react,state,组件,几点,声明,class
来源: https://www.cnblogs.com/art-poet/p/12935815.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有