【问题标题】:dynamic jsx tag name gives error: JSX element type '...' does not have any construct or call signatures动态 jsx 标记名称给出错误:JSX 元素类型“...”没有任何构造或调用签名
【发布时间】:2016-10-13 06:26:47
【问题描述】:

代码:

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

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

我已经阅读了其他与此错误相关的类似问题,但没有一个提供有关如何解决此问题的解决方案。

有人知道吗?

【问题讨论】:

    标签: typescript jsx


    【解决方案1】:

    使用 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>}
    

    只有当表达式的左侧为真时,才会呈现每个组件。

    【讨论】:

    • 感谢您的回复。为什么这是错误的方式?当我希望使用 jsx 呈现动态标签名称时,解决此问题的正确方法是什么
    猜你喜欢
    • 2021-11-30
    • 2016-10-07
    • 2018-02-15
    • 2016-03-05
    • 2021-09-21
    • 2021-12-26
    • 2017-12-05
    • 1970-01-01
    • 2022-06-21
    相关资源
    最近更新 更多