【发布时间】:2021-11-23 15:02:51
【问题描述】:
考虑以下代码,其中包含一个高阶组件、一个函数式组件以及一个使用 HOC 和我们的函数式组件创建的组件:
interface InjectedProps {
someProp?: number;
}
const myHoc = <P extends {}>(
Component: ComponentType<P>
) => ({someProp, ...props}: P & InjectedProps) => {
return <Component {...props as P} />;
}
const MyComponent = (props: {children?: React.ReactNode}) => {
return <div>{props.children}</div>;
};
const WrappedComponent = myHoc(MyComponent);
但是,当我们尝试使用这个新的WrappedComponent:
return (
<WrappedComponent>
<h1>Hello</h1>
<h2>World</h2>
</WrappedComponent>
);
我们最终得到错误:Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & InjectedProps'.。
这可以通过将children props 注入到 HOC 的 props 中来解决,像这样;
interface InjectedProps {
someProp?: number;
children?: React.ReactNode;
}
然而,我们现在遇到的问题是所有包装的组件现在都可以接收子组件,即使它们以前不能。
我的问题是,对于将子组件传递到包装组件中的高阶组件,正确的类型是什么?
【问题讨论】:
标签: reactjs typescript react-native type-inference typescript-generics