gpt4 book ai didi

reactjs - TypeScript:JSX 元素类型没有任何构造或调用签名

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:27 26 4
gpt4 key购买 nike

我正在使用 React 16.2.0、TypeScript 2.7.1,any 不允许作为类型。

主要成分:

// 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.

enter image description here

非常感谢任何提示。谢谢,保罗

最佳答案

您需要告诉编译器该参数是一个构造函数,它返回一个具有属性 languagepathname 的 React 组件

function withMoreInfo<T extends React.Component<{ language: string, pathname: string }, any>>(Wrapped: new (props: { language: string, pathname: string }, context?: any) => 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} />
}
}
}
// The component must have properties language and pathname and only those
class Home extends React.Component<{ language: string, pathname: string }> {
render() {
return <div />
}
}

export default withMoreInfo(Home)

在您调用 withMoreInfo(Home) 的原始版本中,T 确实是一个 React 组件,但是您也可以调用 withMoreInfo (1) 因为 T 没有任何约束。泛型函数对于传递给它的任何类型都必须是正确的,因此编译器认为 T 可能是任何东西,因此它可以可靠地不说任何东西。解决方案是让编译器知道,Wrapped 参数是一个 React 组件的构造函数,即任何具有属性 { 语言的 React 组件 T:字符串,路径名:字符串。构造函数具有与常规函数类似的签名声明,只是带有 new 关键字,因此 new (props: { language: string, pathname: string }, context?: any) = > T

关于reactjs - TypeScript:JSX 元素类型没有任何构造或调用签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com