似乎您的类型不匹配:您的HOC的返回类型为:
React.ComponentType<P & IProps>
但是您实际返回的函数是
(props: IProps) => React.ReactNode
. 如果你成功了
(props: P & IProps) => React.ReactNode
它会停止抱怨。也就是说,我输入这个HOC的方式是:
function withLoader<P extends IProps>(Component: React.ComponentType<P>) {
const Inner: React.FC<P> = props => { // the return type is inferred by the compiler
if (props.loading) {
return (
<div className="overlay">
<div className="loader" />
</div>
)
}
return <Component {...props} />
}
return Inner // return type is React.FC<P>
}
false
一旦它到达您的组件。
最后的想法
当前位置我发现自己正在远离HOC,因为它们很难打字。如果您关心类型安全,您可能更喜欢只使用渲染道具(可能不适用于此用例)或在组件中手动处理它。它可能更详细,但更容易键入,而且更明确。我的意见是:HOC在TypeScript中并不是最容易做到的,所以我很少使用它们。