TypeScript结合React全家桶的一些类型总结(一些常用自带的类型,持续补充)
如果对Typescript不了解的可以先去官方API,学习一波
注意:不用清除的看懂代码,只需要了解类型即可,或者观看我其它博客可以有相应的介绍等
1.React类型总览(包括React本身、router、antd的类型)
1.1 React本身常用类型
无状态组件,函数的类型定义,FunctionComponent<P={}>、简写FC<P={}>
一个泛型接口,可以接受一个参数,可以不传,用来定义props的类型
interface EditorsProps {
detail: string
}
const Editors: React.FC<props: EditorsProps> = () => {
const {
detail } = props;
return (<></>);
};
Component<P,S={}>/PureComponent<P,S={}>
泛型类,接收两个参数,第一个是props的类型定义,第二个是state的类型定义,例如下面的例子(但当有父组件传递属性方法或者定义state的时候还是需要,当没有的情况下省去,和不用TypeScript试用试用一样)
import React, {
Component } from 'react'
import {
connect } from 'react-redux';
import {
asyncAddCount, asyncReduceCount } from '../../store/actions';
import {
RouteComponentProps } from 'react-router-dom';
interface CountProps extends RouteComponentProps {
count: number;
asyncAddCount: (count: number) => void;
asyncReduceCount: (count: number) => void;
}
interface CountStateType{
}
class Counter extends Component<CountProps, CountStateType> {
render():JSX.Element{
const {
count, asyncAddCount, asyncReduceCount } = this.props;
return (
<div>
<h2>{
count}</h2>
<button onClick={
asyncAddCount.bind(null, 10)}>Counter++</button>
<button onClick={
asyncReduceCount.bind(null, 10)}>Counter--</button>
</div>
)
}
}
export default connect(
(state: any) => ({
count: state.getIn(['countReducer', 'count']) }),
{
asyncAddCount, asyncReduceCount }
)(Counter);
JSX.Element
return返回的jsx语法类型,例如上述的render中return的就是这个类型
类的类型就是:ComponentClass<P,S={}>泛型接口,可以在高阶组件中使用,当接收一个类或者函数的时候
import React, {
Context,FC,ComponentClass, createContext, useReducer } from 'react';
const ProviderContext: Context<any> = createContext('provider');
export default (reducer: Function, initialState: any) => (Com: FC<any> | ComponentClass<any,any>) => {
return () => {
const [state, dispatch] = useReducer<any>(reducer, initialState);
return (
<ProviderContext.Provider value={
{
state, dispatch }}>
<Com />
</ProviderContext.Provider >
);
}
}
Dispatch<any>
泛型接口,用于定义dispatch的类型,常常用于useReducer生成的dispatch中
const asyncAction = (dispatch: Dispatch<any>) => {
return {
asyncAddaction() {
console.log('执行addActions之前: ' + Date.now());
setTimeout(() => {
console.log('执行addActions : ' + Date.now());
dispatch(addActions());
}, 1000);
}
}
}
const ProviderContext: Context<any> = createContext('provider');中也可以发现,context的类型就是他的本身,一个泛型接口
interface Context<T> {
Provider: Provider<T>;
Consumer: Consumer<T>;
displayName?: string;
}
FormEvent
:一个react的form表单event的类型,正常结合antd的Form表单使用
<form
onSubmit={
(e: