在react中为了不让别人注入恶意的代码,它都不会自动识别带有标签的字符串,例如这样
export default class Test extends Component{
constructor(props){
super(props)
this.state={html:'<div>213</div>'}
}
componentDidMount(){
}
render(){
return (<div>{this.state.html}</div>)
}
}
这样子它就会当做字符串原样显示出来,这也是为了防止xss攻击,但有时候我们需要这样嵌入标签,就可以用
dangerouslySetInnerHTML
export default class Test extends Component{
constructor(props){
super(props)
this.state={html:'<div>213</div>'}
}
componentDidMount(){
}
render(){
return (
<div>
<div dangerouslySetInnerHTML={{__html:this.state.html}}></div>
</div>
)
}
}
这样子它就会解析div标签