【发布时间】:2021-06-26 07:48:12
【问题描述】:
为了理解问题,我已将示例精简到最低限度:
示例代码 - Hoc.tsx
import React, { FC, ComponentType } from 'react';
import { connect } from 'react-redux';
interface ReduxProps {
param: string;
}
interface InjectedProps {
str: string;
}
const withWrapper = <P extends InjectedProps>(Comp: ComponentType<P>) => {
const Wrapper: FC<ReduxProps> = ({ param }) => {
// do sometthing with param
// inject property
const str = 'hello';
return <Comp str={str} />;
};
Wrapper.displayName = 'Wrapper';
// removed actual state to show example to test in typescript playground
const mapStateToProps = () => ({
param: 'some param'
});
const connector = connect(mapStateToProps);
return connector(Wrapper);
};
export default withWrapper;
在打字稿游乐场我得到这个错误:
错误
类型 '{ str: 字符串; }' 不可分配给类型 'P'。 '{str:字符串; }' 可分配给“P”类型的约束,但“P”可以用约束“InjectedProps”的不同子类型来实例化
如何将 props 注入我的高阶组件并保留提供的泛型?
【问题讨论】:
标签: reactjs typescript higher-order-components