如何在带有 TypeScript 接口的 React 组件中描述方法?

IT技术 reactjs typescript
2021-05-16 22:37:25

我是typescript的大一新生。我不明白我的代码中的这个错误。 在此处输入图片说明

我用IProps来描述类的props。为什么typescript会检查这个类的方法?我怎么解决这个问题?

    export interface IProps extends FormComponentProps {
      dispatch: Dispatch<any>;
      loading: any;
    }

    @Form.create()
    @connect(({ global, loading }) => ({ global, loading }))
    export default class MessageBoard extends PureComponent<IProps> {
      state = {
        activated: false,
      };

      deactivate = () => {
        this.setState({ activated: true });
      };
      ...
      render() {
        ...
        return (...);
      }
    }
1个回答

TypeScript 要求类装饰器不能改变类的类型,而很多在无类型 JavaScript 中经常用作装饰器的 React 高阶组件不符合此规则。不要调用connectandForm.create作为装饰器,尝试将它们作为函数调用并导出结果:

class MessageBoard extends PureComponent<IProps> { ... }

export default Form.create()(
  connect(({ global, loading }) => ({ global, loading }))(
    MessageBoard));