我写了一些代码:

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

我得到一个错误:

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

这是什么意思?


当前回答

import React from 'react';

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

其他回答

这是语法的问题

下面是一个使用TSX的例子:

const SomeMadeComponent = (props: { someText: string }) => {
  const { someText} = props;
  return (
    <div>
      <p>{someText}</p>
    </div>
  );
};

你可以像使用普通组件一样使用它:

<SomeMadeComponent someText='把你的文本放在这里' />

正如@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>

如果你正在使用一个功能组件,并传递一个组件作为道具,对我来说,解决方案是改变React。ReactNode to React。应用的

interface Props{
  GraphComp: React.ElementType
}

const GraphCard:React.FC<Props> = (props) => {
  const { GraphComp } = props;

  return (
   <div> <GraphComp /> </div>
  )
}

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

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

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