【问题标题】:children not being added from custom jsx element未从自定义 jsx 元素添加子项
【发布时间】:2020-10-16 11:01:17
【问题描述】:

我有这样的自定义 Jsx 组件:

const Button = ({title}) => {
   return <div className={title}></div>;
}

我是这样使用的:

<Button title={"ll"}>
    <h1>Some extra custom text</h1>
    <span>span text of button</span>
</Button>

输出如下:

<div class="ll"></div>

但应该是:

<div class="ll">
    <h1>Some extra custom text</h1>
    <span>span text of button</span>
</div>

为什么不添加孩子?

编辑
我正在使用自定义 jsx 工厂。我没有使用反应。

【问题讨论】:

    标签: html typescript nested jsx


    【解决方案1】:

    试试:

    const Button = ({title, children}) => {
       return <div className={title}>{children}</div>;
    }
    

    Edit1:试试这个:

    const h1 = <h1>Some extra custom text</h1>;
    const span = <span>span text of button</span>;
    
    <Button title={"ll"} h1={h1} span={span}></Button>
    
    const Button = ({title, h1, span}) => {
       return <div className={title}>{h1}{span}</div>;
    }
    

    Edit2:试试这个:

    const Button = (props) => {
        return <div className={props.title}>{props.children}</div>;
    }
    
    <Button title={"ll"}>
      <h1>Some extra custom text</h1>
      <span>span text of button</span>
    </Button>
    

    【讨论】:

    • 我已经尝试过了:) 但它在我使用按钮作为 jsx 的那一行出现错误,因为缺少一个参数。 &lt;Button title={ll}&gt; 这就是我所说的。这是完整的错误:Property 'children' is missing in type '{ title: string; }' but required in type '{ title: any; children: any; }'
    • 你在使用 typeScript 吗?
    • 我更新了另一件事以尝试在我的原始答案中
    • 它说:JSX fragment is not supported when using --jsxFactory 我通过用 div 替换空标签来修复它。但这感觉就像违背了 jsx 的目的,不是吗?
    • 我又添加了一件你可以做的事情,而不是解构道具,直接将它作为一个对象传递。这绝对是 typeScript 的东西;如果这不起作用,请尝试编辑 1,但使用 span 标签而不是片段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 2020-12-07
    • 2022-10-18
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多