我有一个需要从父母(使用PropA)和HOC(使用PropB)注入的组件
export interface PropsA extends PropsB {
propA: string;
}
class SomeComponent extends React.PureComponent<PropsA> {
render(){
return (
<div>
{this.props.propA}
{this.props.propB}
</div>
);
}
}
export default withPropsB(SomeComponent);
export interface PropsB {
propB: string;
}
这是我们用HOC注入它的方式:
export const withPropsB = (Component: any) => {
class EnhancedWithProsB extends React.Component<PropsB> {
render(){
return <Component {...this.props}/>;
}
}
const mapStateToProps = (state: any) => ({
propB: "propB"
});
return connect(mapStateToProps)(EnhancedWithProsB);
};
客户以这种方式使用它:
class Wrapper extends React.Component {
render(){
return <SomeComponent propA="propA" />;
}
}
我得到的错误是&#34; Property&#39; propA&#39;类型&#39; IntrinsicAttributes&amp; IntrinsicClassAttributes,ComponentState&gt;&gt; &安培; ...&#39;&#34;
withPropsB方法应返回什么类型才能使此错误消失?
答案 0 :(得分:3)
您需要从EnhancedWithProsB
派生React.Component
,并使用与传递的组件相同的道具(在您的情况下为PropsA
)。通用的方法是:
export const withPropsB = <T extends PropsB>(Component: new(... p: any[])=> React.PureComponent<T>) => {
class EnhancedWithProsB extends React.Component<T> {
render(){
return <Component {...this.props}/>;
}
}
const mapStateToProps = (state: any) => ({
propB: "propB"
});
return connect(mapStateToProps)(EnhancedWithProsB);
};