我正在使用react和typescript以及hoist-non-react-statics并试图创建一个HOC。我已经将代码简化为一个人为的HOC,它用div包装组件。
const withWrapper = <TProps extends {}>(
WrappedComponent: React.ComponentType<TProps>,
) => {
const WithWrapper: React.FC<TProps> = (props: TProps) => (
<div>
<WrappedComponent {...props} />
</div>
)
WithWrapper.displayName = `WithWrapper(${
WrappedComponent.displayName || WrappedComponent.name || 'Component'
})`
return hoistNonReactStatics(WithWrapper, WrappedComponent)
}
但得到错误:
Argument of type 'ComponentType<TProps>' is not assignable to parameter of type 'ComponentType<any>'.
Type 'ComponentClass<TProps, any>' is not assignable to type 'ComponentType<any>'.
Type 'ComponentClass<TProps, any>' is not assignable to type 'FunctionComponent<any>'.
Type 'ComponentClass<TProps, any>' provides no match for the signature '(props: any, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | any | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
return hoistNonReactStatics(WithWrapper, WrappedComponent)
~~~~~~~~~~~~~~~~
为什么这个无效?让它通过的唯一方法是通过施放WrappedComponent as React.ComponentType<any>
。
编辑:[email protected] @ types / react @ 16.8.4 @ types / hoist-non-react-statics @ 3.0.1
您的代码可以与[email protected]
,@types/[email protected]
和@types/[email protected]
一起使用。
代码中唯一不正确的事情是使用单个管道(|
)而不是双管道。单个管道用于按位OR,而double用于短路 - 我相信你的意思是后者。