我正在使用React 16.2.0,TypeScript 2.7.1,并且不允许任何类型 .
主要组成部分:
// index.js
import * as React from 'react'
import Page from './page'
import i18n from '../i18n'
import PageContent from '../components/pageContent'
import withMoreInfo from '../hoc/withMoreInfo'
class Home extends React.Component {
render () {
return <Page title={ i18n.t('home.title') }>
<PageContent />
</Page>
}
}
export default withMoreInfo(Home)
特别文件:
import * as React from 'react'
export default function withMoreInfo<T> (Wrapped: T) {
return class WithMoreInfo extends React.Component<{ asPath: string }> {
static async getInitialProps ({ asPath }: { asPath: string }) {
return { asPath }
}
render () {
const { asPath } = this.props
const language = asPath.indexOf('/ro') === 0 ? 'ro' : 'en'
return <Wrapped language={ language } pathname={ asPath } />
}
}
}
我无法解决此错误: error #TS2604: JSX element type 'Wrapped' does not have any construct or call signatures.
非常感谢任何提示 . 谢谢,保罗
1 回答
您需要告诉编译器该参数是一个构造函数,并返回一个具有属性
language
和pathname
的React组件在您调用
withMoreInfo(Home)
的原始版本中,T
确实是一个反应组件,但是你可以调用withMoreInfo(1)
,因为T
绝不受约束 . 对于传递给它的任何类型,泛型函数必须是正确的,因此编译器认为T
可能是任何东西,所以它可以可靠地对它一无所知 . 解决方案是让编译器知道Wrapped
参数是反应组件的构造函数,即具有{ language: string, pathname: string }
属性的任何反应组件T
. 构造函数具有与常规函数类似的签名声明,只有new
关键字,因此new (props: { language: string, pathname: string }, context?: any) => T