我正在使用react和typescript和hoist-non-react-statics并尝试创建HOC。我已将代码简化为只用div包裹组件的人为HOC。
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>
。
编辑:typescript@2.9.2 @ types / react @ 16.8.4 @ types / hoist-non-react-statics @ 3.0.1
答案 0 :(得分:0)
您的代码可以与typescript@3.3.1
,@types/react@16.8.4
和@types/hoist-non-react-statics@3.0.1
一起正常工作。
代码中唯一不正确的事情是使用单个管道(|
)而不是双管道。单个管道用于按位“或”,而双管道则用于短路-我相信您的意思是后者。