gpt4 book ai didi

javascript - 在 React 中动态选择标签

转载 作者:行者123 更新时间:2023-11-30 09:59:38 25 4
gpt4 key购买 nike

我有一些使用 SVG 的 React 组件,可以包含或不包含在 SVG 中。因此,我希望有一种简单的方法让它们在 svgg 中呈现,具体取决于参数,例如:

export default class SVGComponent extends React.Component{
get containerElement() {
return this.props.inSVG ? 'g' : 'svg';
}
render() {
return(<{containerElement}>
<text>Extendable component</text>
</{containerElement}>);
}
}

这是行不通的:您不能以这种方式在 JSX 中使用模板注入(inject)。还有另一种方法可以解决吗?看起来我可以做 React.DOM[containerElement],但我想 React 不喜欢混合 React.DOM 和 JSX,我不想完全转向 React。 DOM 语法仅用于这一功能。

最佳答案

看看这个答案Dynamic tag name in jsx and React

看来你可以创建一个首字母大写的变量并像这样的组件一样使用它

const CustomTag = `h${this.props.priority}`;
<CustomTag>Hello</CustomTag>

如果this.props.priority == 3这将呈现 <h3>Hello</h3>

关于javascript - 在 React 中动态选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32352600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com