我写了一些代码:

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)样式组件,则使用

变量

其他回答

这是语法的问题

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

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

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

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

这是我搜索错误时的第一个结果,所以我想在我的特定情况下分享解决方案:

我正在使用的库是这样的:

export { default as Arc } from './shapes/Arc';

我导入错误,导致错误:

import Arc from "@visx/shape";

它应该是

import { Arc } from "@visx/shape";

在我的例子中,我在类型定义中缺少new。

some-js-component.d。ts文件:

import * as React from "react";

export default class SomeJSXComponent extends React.Component<any, any> {
    new (props: any, context?: any)
}

在tsx文件中,我试图导入非类型化组件:

import SomeJSXComponent from 'some-js-component'

const NewComp = ({ asdf }: NewProps) => <SomeJSXComponent withProps={asdf} />

你可以使用

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

但是,下面的方法有用吗?

function renderGreeting(Elem: React.ComponentType) {
    const propsToPass = {one: 1, two: 2};

    return <span>Hello, <Elem {...propsToPass} />!</span>;
}

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

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

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