我写了一些代码:

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

我得到一个错误:

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

这是什么意思?


当前回答

当我从JSX转换到TSX时,我们保留了一些库作为js/ JSX,并将其他库转换为ts/ TSX,我几乎总是忘记更改TSX\ ts文件中的js/ JSX导入语句

import * as ComponentName(组件名);

to

import ComponentName from "ComponentName"

如果从TSX调用旧的JSX (React.createClass)样式组件,则使用

变量

其他回答

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

如果你将功能组件作为道具传递给另一个组件,请使用以下命令:

import React from 'react';

type RenderGreetingProps = {
  element: React.FunctionComponent<any>
};

function RenderGreeting(props: RenderGreetingProps) {
  const {element: Element} = props;

  return <span>Hello, <Element />!</span>;
}

这是语法的问题

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

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

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

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

如果你想把一个组件类作为参数(而不是一个实例),使用React。ComponentClass:

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

我通过在导出组件之前使用Type Assertions来解决这个问题。TypeScript在使用redux 'compose'组合后无法识别,因此我将道具类型分为IParentProps和IProps,并在做类型断言时使用IParentProps

import { compose } from 'react-redux'
import HOC1 from 'HOCs/HOC1'
import HOC2 from 'HOCs/HOC2'

type IParentProps = {}
type IProps = {}

const Component: React.FC<IProps & IParentProps> = React.memo((props) => {

      return <SomeComponent {...props}/>

})

return compose(HOC1,HOC2)(Component) as React.FunctionComponent<IParentProps>