jsx和React中的dynamic标签名称
我尝试写一个React组件。 用于html标题标签(h1,h2,h3等),其中标题优先级根据我们在道具中定义的优先级dynamic改变。
这里我试着去做。
<h{this.props.priority}>Hello</h{this.props.priority}> 
预期产出:
 <h1>Hello</h1> 
这不起作用。 有没有可能的方法来做到这一点?
没有办法做到这一点,只是把它放在一个variables(首字母大写):
 const CustomTag = `h${this.props.priority}`; <CustomTag>Hello</CustomTag > 
 为了完整React.createElement ,如果您想使用dynamic名称,您也可以直接调用React.createElement而不是使用JSX: 
 React.createElement(`h${this.props.priority}`, null, 'Hello') 
这避免了必须创build一个新的variables或组件。
道具:
 React.createElement( `h${this.props.priority}`, { foo: 'bar', }, 'Hello' ) 
从文档 :
创build并返回给定types的新React元素。 types参数可以是标签名称string(如
'div'或'span'),也可以是React组件types(类或函数)。使用JSX编写的代码将被转换为使用
React.createElement()。 如果您使用的是JSX,则通常不会直接调用React.createElement()。 请参阅不使用JSX的React以了解更多信息。