我写了一些代码:

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

我得到一个错误:

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

这是什么意思?


当前回答

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

interface Props{
  GraphComp: React.ElementType
}

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

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

其他回答

在我的例子中,我在类型定义中缺少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} />

如果你使用的是material-ui,转到组件的类型定义,它是由TypeScript下划线。你很可能会看到这样的东西

export { default } from './ComponentName';

你有两个选项来解决这个错误:

1.在JSX中使用组件时添加.default:

import ComponentName from './ComponentName'

const Component = () => <ComponentName.default />

2.在导入时,将组件重命名为“default”:

import { default as ComponentName } from './ComponentName'

const Component = () => <ComponentName />

这样就不需要每次使用组件时都指定.default。

这是构造函数和实例之间的混淆。

记住,当你在React中编写一个组件时:

class Greeter extends React.Component<any, any> {
    render() {
        return <div>Hello, {this.props.whoToGreet}</div>;
    }
}

你可以这样用:

return <Greeter whoToGreet='world' />;

你不能这样用:

let Greet = new Greeter();
return <Greet whoToGreet='world' />;

在第一个例子中,我们传递了组件的构造函数Greeter。这是正确的用法。在第二个例子中,我们传递了一个Greeter实例。这是不正确的,将在运行时失败,并出现类似“对象不是函数”的错误。


这段代码的问题

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

它期待一个React.Component的实例。你需要的是一个带有React构造函数的函数。组件:

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

或类似的:

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

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

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

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

interface Props{
  GraphComp: React.ElementType
}

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

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