我写了一些代码:

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

我得到一个错误:

JSX元素类型Elem没有任何构造或调用签名

这是什么意思?


当前回答

正如@Jthorpe所提到的,ComponentClass只允许Component或PureComponent,而不允许FunctionComponent。

如果你试图传递一个FunctionComponent, typescript将抛出一个类似于…

Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.

但是,通过使用ComponentType而不是ComponentClass,可以同时满足这两种情况。根据react声明文件,类型定义为…

type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>

其他回答

以下方法对我有用:https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019我通过这样做来修复它:

const Component = (isFoo ? FooComponent : BarComponent) as React.ElementType

当声明React Class组件时,使用React。ComponentClass而不是React。组件,那么它将修复ts错误。

就我而言,我使用的是React。ReactNode作为功能组件的类型,而不是React。FC型。

准确地说,在这个组件中:

export const PropertiesList: React。FC = (props: any) => { Const列表:string[] = [ 《后果:Phasellus sollicitudin》, 《后果:Phasellus sollicitudin》, “……” ] 回报( <列表 header={<ListHeader header= "Properties List" />} 数据源={}列表 renderItem={(listItem, index) => <列表。项目键={index}> {listItem} </List. index . > {listtitem}项> } /> ) }

看起来现在有一个特殊的新TypeScript类型来解决这个问题:JSXElementConstructor。如果你让某人将构造函数传递给一个未知的ReactElement,而不是该ReactElement的实例,这是传递的正确类型。

const renderGreeting = (Elem: JSXElementConstructor<any>) => {
    return <span>Hello, <Elem />!</span>;
}

这等价于上面选择的正确答案,因为:在JSX中使用<Elem />(也就是用尖括号将大写变量括起来)等效于使用new关键字调用JSX元素的构造函数。

import React from 'react';

function MyComponent (
  WrappedComponent: React.FunctionComponent | React.ComponentClass
) {
  return (
    <Wrapper>
      <WrappedComponent />
    </Wrapper>
  );
}