【问题标题】:How to correctly type react HOC with Typescript如何使用 Typescript 正确输入 react HOC
【发布时间】:2020-10-22 15:03:29
【问题描述】:

我是 Typescript 的新手,我不知道如何用它正确键入 HOC。我已经花了一整天的时间来弄清楚它没有任何成功。我有一个非常基本的代码 sn-p 和 BaseComponent 和一个简单的 HOC。由于某种原因,在创建 BaseComponent 时,我收到 Typescript 错误:

Type '{ total: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'. Property 'total' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ children?: ReactNode; }> & Readonly<...>'.

知道如何正确设置 Prop 类型吗?

基础组件:

interface SummaryProps {
    sum: number;
}

class Summary extends React.Component<SummaryProps> {
    render() {
        return (
            <div>{this.props.sum}</div>
        );
    }
}

export default withMyHOC(Summary);

HOC:

interface WithMyHOCProps {
    total: number;
}

const withMyHOC = (WrappedComponent: React.ComponentType<any>): React.ComponentClass => {
    return class extends React.Component<WithMyHOCProps> {
        render() {
            return (
                <WrappedComponent
                    {...this.props}
                    sum={this.props.total + 1}
                />
            );
        }
    };
};

export default withMyHOC;

初始化:

import Summary from 'features/Summary.tsx';

<Summary total={5} /> // here I am getting Typescript error described above

【问题讨论】:

标签: reactjs typescript react-props high-order-component


【解决方案1】:

通过传递{...this.props},您也将withMyHOC 的所有道具传递给底层组件。这也包括total,但Summary 没有属性“total”。

所以 oyu 也需要为孩子添加所有的道具。

【讨论】:

  • 我删除了{...this.props},但仍然收到相同的错误消息。我还尝试将totaltype 添加到Summary- 也得到了同样的错误。
猜你喜欢
  • 2019-02-22
  • 1970-01-01
  • 2021-04-14
  • 2017-06-17
  • 2021-11-05
  • 2019-01-22
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多