1.使用场景
dangerouslySetInnerHTML指令能将字符串当做html解析 相当于vue中的v-html指令 一般我们用来渲染富文本返回的html文本2.使用方法
{this.state.tolist.map((item,index)=>{ return ( <span dangerouslySetInnerHTML={{__html:item}} key={index}> </span> ) })}
将这个指令绑定的一个html标签上即可
_html:要解析的htm代码 下面是将前面的tolist案例和dangerouslySetInnerHTML相结合输入
<div style="color:red">红色</div>
字符串被解析为了html代码
3.完整代码
import React, { Component } from 'react' import './css/01-index.css' export default class App extends Component { state = { tolist:[], inputValue:'' } render() { return ( <div> <input value={this.state.inputValue} onChange={ this.changeHanlder } type="text" /> <button onClick={ this.addHanler }>add</button> {this.state.tolist.map((item,index)=>{ return ( <span dangerouslySetInnerHTML={{__html:item}} key={index}> </span> ) })} <div className={this.state.tolist.length>0 ? 'hidden' : ""}>暂无代办事项</div> </div> ) } changeHanlder = (e)=>{ this.setState({ inputValue:e.target.value }) } addHanler = ()=>{ if(this.state.inputValue !==''){ const newlist = [...this.state.tolist] newlist.push(this.state.inputValue) this.setState({ tolist:newlist, inputValue:'' }) } } }
标签:tolist,14,index,指令,state,React,dangerousSetinnerHtml,html,inputValue From: https://www.cnblogs.com/SadicZhou/p/17778619.html