React中使用TypeScript

新建 react + typescript 项目:

npx create-react-app my-app --typescriptnode

已有项目迁移到typescript:

npm install --save typescript @types/node @types/react @types/react-dom @types/jestreact

TypeScript入门教程
git

1.引入插件

typescript中引入外部插件除了要引入插件自己还要引入它的声明@types,@type统一管理第三方库的声明文件。
好比: 引入路由插件react-router-dom
npm i react-router-dom    还需    npm i @types/react-router-dom
github

查找声明文件:microsoft.github.io/TypeSearch/typescript

2.ts中路由配置

前文我有说过react中的路由, 可是在ts环境里你会发现引入@types/react-router-dom后直接使用withRouterts会一直报错(ts2339), 缘由是必需使用 RuoteComponentProps,。npm

import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';

type PropsType = RouteComponentProps & {};

class demo extends React.Component<PropsType, any> {
  
  constructor(props: PropsType) {
    super(props);
    this.state = {
      demo: 'demo',
    }
  }

  goBack() {
    this.props.history.goBack();
  }

  render() {
    return (
      <div>
        <button onClick={() => this.goBack()}>goBack</button>
      </div>
    )
  }
}

export default withRouter(demo);
复制代码

3.props、state的使用

ts中React的组件中使用props或者state的时候,须要给组件传两个参数:指定类型(types)和对象的形(shape),缘由是ts的规则一切都应该按住预期的方式工做,类型检查方面得先定义。bash

React.Compnent<types, shape>
复制代码

若是类型对不上ts会提示报错: react-router

应该对应类型: app

当你不肯定本身须要建立多少参数和参数类型时,建议使用any(任意类型):dom

class demo extends React.Component<any, any>
复制代码

给组件传入 RuoteComponentProps 后就至关于定义了 any , 若是是没有使用路由插件的普通组型,须要注意若是React.Compnent<types, shape>中的types被定义了,则没办法接手来自路由的参数。

this.props.history.push({
  pathname: 'demo',
  state: {
    data: 1
  }
})
复制代码
一样的咱们能够把 demoData 改成 any 来解决。

吐槽:React + TypeScript 一开始摸起来真的是很是多问题,由于第一次使用ts也是不少不习惯,加上还要适应react路由插件的声明和各类特殊处理...

相关文章
相关标签/搜索