gpt4 book ai didi

javascript - 如何将字符串转换为jsx?

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

如何将此字符串转换为 jsx?我希望此字符串显示为 HTML 元素。

this.setState({
input: "<h1 id="heading">Heading</h1> <h2 id="sub-heading">Sub-heading</h2> <h3 id="another-deeper-heading">Another deeper heading</h3>"
});

render() {
return <div>{this.state.input}</div>
}

最佳答案

在 JSX 中不需要引用 HTML 元素,但是一个 HTML 元素只能有一个父元素。去掉引号,将 div 移至变量,一切就绪。

所以:

this.setState({
input: <div><h1 id="heading">Heading</h1> <h2 id="sub-heading">Sub-heading</h2> <h3 id="another-deeper-heading">Another deeper heading</h3></div>
});

render() {
return this.state.input
}

不过,我不确定您从中得到了什么。最佳做法是将简单数据保存在 propsstate 中,并将 HTML 包装器放在渲染函数中,而不是在 state 中。

关于javascript - 如何将字符串转换为jsx?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223063/

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