将字符串转译为可解析的html代码,dangerouslySetInterHTML

zhuanbike 2022-1-2 756

第一次见这么长的方法

 class Com extends React.Component{
                constructor(props){
                    super(props)
                    this.state={
                        name:"西西",
                        newHtml:"<p>我是state中的内容</p>"
                    }
                }
                fun=()=>{
                    this.setState({
                        name:"haha"
                    },()=>{
                        console.log(this.state.name) //回调定义后的name
                    })
                 
                }
                render(){
                    return(
                       <div>
                       <button onClick={this.fun}>点我修改</button>
                        {this.state.name}
                        <div>{this.state.newHtml}</div> //这样输出的是字符串,不解析html
                           {/* 字符串标签插入的话  dangerouslySetInnderHTML={{__HTML:你要插入的字符串}}*/}
                        <div dangerouslySetInnerHTML={{__html:this.state.newHtml}} /> //通过这个解析HTML
                       </div> 
                    )
                }
            }
               
            ReactDOM.render(<Com />,document.getElementById("demoReact"));


最新回复 (1)
  • zhuanbike 2022-1-2
    0 引用 2
    为了节省时间,这个就不手写了,直接粘贴过来,作为一个state的标准件
发新帖