What does the error “JSX element type '…' does not have any construct or call signatures” mean?

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I wrote some code:

function renderGreeting(Elem: React.Component) {     return Hello, !; }

I'm getting an error:

JSX element type Elem does not have any construct or call signatures

What does it mean?

回答1:

This is a confusion between constructors and instances.

Remember that when you write a component in React:

class Greeter extends React.Component {     render() {         return 
Hello, {this.props.whoToGreet}
; } }

You use it this way:

return ;

You don't use it this way:

let Greet = new Greeter(); return ;

In the first example, we're passing around Greeter, the constructor function for our component. That's the correct usage. In the second example, we're passing around an instance of Greeter. That's incorrect, and will fail at runtime with an error like "Object is not a function".


The problem with this code

function renderGreeting(Elem: React.Component) {     return Hello, !; }

is that it's expecting an instance of React.Component. What you want a function that takes a constructor for React.Component:

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

or similarly:

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


回答2:

If you want to take a component class as a parameter (vs an instance), use React.ComponentClass:

function renderGreeting(Elem: React.ComponentClass) {     return Hello, !; }


回答3:

When I'm converting from JSX to TSX and we keep some libraries as js/jsx and convert others to ts/tsx I almost always forget to change the js/jsx import statements from

import * as ComponentName from "ComponentName";

to

import ComponentName from "ComponentName";

for tsx



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!