Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将字符串转换为jsx?_Javascript_Reactjs_React Jsx - Fatal编程技术网

Javascript 如何将字符串转换为jsx?

Javascript 如何将字符串转换为jsx?,javascript,reactjs,react-jsx,Javascript,Reactjs,React Jsx,如何将此字符串转换为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

如何将此字符串转换为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>
} 
this.setState({
输入:“标题子标题另一个更深的标题”
});
render(){
返回{this.state.input}
} 

您不需要在JSX中引用HTML元素,但HTML元素只能有一个父元素。去掉引号,将div向上移动到变量,就可以全部设置好了

因此:

this.setState({
输入:标题子标题另一个更深的标题
});
render(){
返回此.state.input
} 

不过,我不确定你从中得到了什么。最佳做法是将简单数据保存在
props
state
中,并将HTML包装器放在呈现函数中,而不是放在
state
中,只是为了突出显示解决方案,@user633183的注释:

使用
危险的LysetinerHTML


我得到的响应是一个包含html元素的字符串。我已将该数据存储在状态中,最后我尝试将该字符串呈现为jsx,但我在结果中得到的不是标题,而是标题。@Bernardo然后您唯一的选择是使用
DangerouslySetinerHTML
@naomik谢谢DangerouslySetinerHTML解决了我的问题。这是一个反模式
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
}