jsx和React中的动态标签名称

node.js Node.js

宝儿Sam

2020-03-11

我尝试编写一个React组件。对于html标题标签(h1,h2,h3等),其中标题优先级根据我们在道具中定义的优先级动态变化。

这是我尝试做的。

<h{this.props.priority}>Hello</h{this.props.priority}>

预期输出:

<h1>Hello</h1>

这是行不通的。有什么可能的方法可以做到这一点?

第662篇《jsx和React中的动态标签名称》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
LEY古一阿飞 2020.03.11

在动态标题(h1,h2 ...)的情况下,组件可以像这样返回React.createElement(上面由Felix提到)。

const Heading = ({level, children, ...props}) => {
    return React.createElement(`h${level}`, props , children)
}

为了可组合性,道具和孩子都被传递。

参见示例

TomGO小小 2020.03.11

无法就地执行此操作,只需将其放在变量中(首字母大写):

const CustomTag = `h${this.props.priority}`;

<CustomTag>Hello</CustomTag>

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android