How to use React HOC with Typescript
我是Typescript的新手,我想使用React HOC(高阶组件)。我需要使用功能intlWrapper将每个组件包装到名为IntlContext的提供程序上下文中。我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import * as React from 'react'; import * as _ from 'lodash'; import {IntlContext} from '../intl'; export default function intlWrapper < T > (WrappedComponent: React.ComponentClass< T >){ return class IntlReceiver extends React.Component < T >{ render() { return ( <IntlContext.Consumer> { locale=><WrappedComponent {...this.props} locale={locale}/> } </IntlContext.Consumer> ) } } } |
但是我遇到了complie错误。
1 | (10,55): Property 'locale' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<T, any, any>> & Readonly<{ children?: ReactNode; }> & Readonly< T >'. |
如果我更改为任何代码,则该代码有效。但是,当我使用WrappedComponent时,接口中定义的PropTypes会因为包装而丢失。
这个问题有解决方案吗?
您具有
您可以通过添加例如