[英]How to correctly type react HOC with Typescript
I am new to Typescript and I cannot figure out how to correctly type HOC with it.我是 Typescript 的新手,我不知道如何用它正确键入 HOC。 I already spent all day to figure it out without any success.
我已经花了一整天的时间来解决它,但没有任何成功。 I am having very basic code snippet with
BaseComponent
and one simple HOC
.我有
BaseComponent
和一个简单的HOC
非常基本的代码片段。 For some reason, when creating the BaseComponent, I am getting Typescript error:出于某种原因,在创建 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<...>'
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<...>'
. 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<...>'
。
Any idea how to correctly set up Prop types?知道如何正确设置 Prop 类型吗?
BaseComponent:基础组件:
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;
Initialization:初始化:
import Summary from 'features/Summary.tsx';
<Summary total={5} /> // here I am getting Typescript error described above
By passing {...this.props}
, you are passing all the props of withMyHOC
to the underlying component as well.通过传递
{...this.props}
,您也将withMyHOC
所有道具withMyHOC
给底层组件。 This includes total
as well, but Summary
does not have the prop 'total'.这也包括
total
,但Summary
没有道具“总计”。
So oyu need to add all props to the child as well.所以oyu也需要为孩子添加所有道具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.