动态 JSX 标记名称给出错误:JSX 元素类型"..."没有任何构造或调用签名



代码:

const TagName = 'div';
const element = <TagName>....</TagName> // line 2

这在第2行出现错误:JSX element type 'TagName' does not have any construct or call signatures.

我读过其他关于这个错误的类似问题,但没有一个提供如何解决这个问题的解决方案。

有人知道吗?

使用JSX时,标记名不是变量值,而是组件。

例如:

文件B:

export class ComponentB extends ReactComponent{
}

文件A:

import {ComponentB} from 'b';
<ComponentB></ComponentB>

但是,如果出于某种原因,你想使用一个变量来拥有一个动态tagName(无论如何,这是一种错误的方法(,那么你需要使用大括号,这会使它们的内容解析为JavaScript:

const TagName = 'div';
const element = <{TagName}>....</{TagName}> // line 2

这是一种错误的方式,因为这不是一种常见的做法,因此其他阅读您代码的程序员不会清楚。

通常的做法是这样的:

const someCondition = 1 + 1 === 2;
{someCondition && 
<ComponentA></ComponentA>}
{!someCondition && 
<ComponentB></ComponentB>}

只要表达式的左侧为true,就会渲染每个组件。

相关内容

最新更新