新建 react + typescript 项目:
npx create-react-app my-app --typescript
已有项目迁移到typescript:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
1.引入插件
typescript中引入外部插件除了要引入插件本身还要引入它的声明@types,@type统一管理第三方库的声明文件。
比如:
引入路由插件react-router-dom
npm i react-router-dom
还需 npm i @types/react-router-dom
查找声明文件:microsoft.github.io/TypeSearch/
2.ts中路由配置
前文我有说过react中的路由,
但是在ts环境里你会发现引入@types/react-router-dom
后直接使用withRouter
ts会一直报错(ts2339),
原因是必需使用 RuoteComponentProps,。
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的规则一切都应该按住预期的方式工作,类型检查方面得先定义。
React.Compnent<types, shape>
复制代码
如果类型对不上ts会提示报错:
应该对应类型:
当你不确定自己需要创建多少参数和参数类型时,建议使用any(任意类型):
class demo extends React.Component<any, any>
复制代码
给组件传入 RuoteComponentProps 后就相当于定义了 any ,
如果是没有使用路由插件的普通组型,需要注意如果React.Compnent<types, shape>
中的types被定义了,则没办法接手来自路由的参数。
this.props.history.push({
pathname: 'demo',
state: {
data: 1
}
})
复制代码
吐槽:React + TypeScript 一开始摸起来真的是非常多问题,因为第一次使用ts也是很多不习惯,加上还要适应react路由插件的声明和各种特殊处理...