Dynamic tag name in React JSX

题意: 在 React JSX 中的动态标签名"

问题背景:

I am trying to write a React component for HTML heading tags (h1h2h3, etc.), where the heading level is specified via a prop.

我正在尝试编写一个 React 组件,用于 HTML 标题标签(h1、h2、h3 等),其中标题级别通过一个属性指定。

I tried to do it like this:

我尝试这样做:

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

And I expected output like:

我期望的输出是:

<h1>Hello</h1>

But this is not working.

但这不起作用。

Is there any way to do this?

有没有办法做到这一点?

问题解决:

No way to do that in-place, just put it in a variable (with first letter capitalised):

没有办法直接这样做,只需将其放入一个变量中(首字母大写):

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

<CustomTag>Hello</CustomTag>

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143426336