ts中使用高阶组件

在TS中,编译器会对装饰器作用的值做签名一致性检查,而我们在高阶组件中一般都会返回新的组件,并且对被作用的组件的 props
进行修改(添加、删除)等。这些会导致签名一致性校验失败, TS
会给出错误提示。

为了解决此类问题。我们不能直接export高阶组件。以React为例,

使用antd的form组件时

我们需要导出组件

Form.create()(YourComponent)

如此返回的是新组件。ts校验不通过,正确的姿势为

import { Form } from 'antd';
import { FormComponentProps } from 'antd/lib/form';

interface UserFormProps extends FormComponentProps {
  age: number;
  name: string;
}

class UserForm extends React.Component<UserFormProps, any> {
  // ...
}

const App = Form.create<UserFormProps>({
  // ...
})(UserForm);
使用react-router-dom的WithRouter方法时

直接使用withRouter(YourComponent)仍然不行。正确的姿势为

import * as React from 'react'
import { withRouter } from 'react-router-dom';
import {RouteComponentProps} from "react-router";

// this.props.match.params.*的属性
type PathParamsType = {
    param1: string,
}

// 组件自己的属性
type PropsType = RouteComponentProps<PathParamsType> & {
    someString: string,
}

class YourComponent extends React.Component<PropsType> {
    render() {
        return <div>...</div>;
    }
}

export default withRouter(YourComponent);

参考链接:
优雅的在 react 中使用 TypeScript
withRouter异常处理

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容