react:innerHTML的替代方案dangerouslySetInnerHTML

dangerouslySetInnerHTML 是 React 为浏览器 DOM 提供 innerHTML 的替换方案。通常来讲,使用代码直接设置 HTML 存在风险,因为很容易无意中使用户暴露于跨站脚本(XSS)的攻击。因此,你可以直接在 React 中设置 HTML,但当你想设置 dangerouslySetInnerHTML 时,需要向其传递包含 key 为 __html 的对象,以此来警示你。

例:

<div dangerouslySetInnerHTML={
     {
          __html: `<div style="width:100px; height:50px; border:1px solid #ccc; color:red; font-size:14px;">这是一段HTML</div>`
     }
}></div>

 

export default class App extends Component {
    addTodoItem = () => {
        let newList = JSON.parse(JSON.stringify(this.state.list))
        newList.push({
            id: Math.random() * 100,
            name: this.input.current.value
        })
        this.setState({
            list: newList
        })
        this.input.current.value = '';
    };
    delTodoItem = (index) => {
        let newList = JSON.parse(JSON.stringify(this.state.list))
        newList.splice(index, 1);
        this.setState({
            list: newList
        })
    }
    state = {
        list: [
            {
                id: 1,
                name: '吃饭'
            },
            {
                id: 2,
                name: '睡觉'
            },
            {
                id: 3,
                name: '打豆豆'
            }
        ]
    }
    input = React.createRef();
    render() {
        return (
            <div>
                <input ref={this.input} />
                <button
                    onClick={() => {
                        return this.addTodoItem();
                    }}
                >
                    add
                </button>

                {this.state.list.map((item, index) => {
                    return (
                        <p key={item.id}>
                            {/* {item.name} */}
                            {/* 富文本展示,慎用 */}
                            <span dangerouslySetInnerHTML={
                                {
                                    __html: item.name
                                }
                            }></span>
                            <button onClick={() => { this.delTodoItem(index) }}>del</button>
                        </p>

                    );
                })}
                <p style={
   
   { display: (this.state.list.length > 0 ? 'none' : 'block') }}>暂无待办事项</p>
            </div>
        );
    }
}

 

 注:dangerouslySetInnerHTML中不仅仅可以设置内容为一个和HTML片段,也可以是一个普通的字符串。使用dangerouslySetInnerHTML时必须要慎重,必须确定内容源是可靠的。

跨站脚本(XSS):将恶意链接出入到html中,诱导点击被伪装后的链接,以此非法获取用户信息等。

猜你喜欢

转载自blog.csdn.net/m0_47135993/article/details/127475105