簡體   English   中英

如何在React中處理第三方dom操縱?

[英]How to handle third-party dom manipulation in React?

我是React的新手,不確定如何處理以下情況:

我制作了一個呈現代碼並使用Highlight.js突出顯示語法的組件。
它有效,但是在內容更新時中斷了。

class CodeBox extends React.Component {
    componentDidMount() {
        this.highlight();
    }
    componentDidUpdate() {
        this.highlight();
    }
    highlight() {
        hljs.highlightBlock(this.elem);
    }
    render() {
        return (
            <pre><code ref={(elem) => { this.elem = elem }}>{this.props.code}</code></pre>
        );
    }
}

我的理解是React處理code節點,並且不喜歡Highlight.js對其進行篡改...所以我訴諸於此:

class CodeBox extends React.Component {
    componentDidMount() {
        this.highlight();
    }
    componentDidUpdate() {
        this.highlight();
    }
    highlight() {
        this.elem.innerHTML = "";
        let c = document.createElement("code");
        c.innerHTML = this.props.code;
        this.elem.appendChild(c);
        hljs.highlightBlock(c);
    }
    render() {
        return (
            <pre ref={(elem) => { this.elem = elem }}></pre>
        );
    }
}

哪個可行,但現在我感覺我使用React錯誤。
有沒有辦法不涉及直接操縱dom的方法呢?

您可以使用dangerouslySetInnerHTML地設置內部HTML來獲得相同的結果,而無需在渲染后使用引用或更改DOM,但是由於Highlight.js工作方式,您仍然必須使用偽造的HTML元素。

要做到這一點,而不是使用componentDidUpdatecomponentDidMount方法,我們可以使用componentWillMountcomponentWillReceiveProps方法如下所示:

componentWillMount() {
    this.highlight(this.props);
}
componentWillReceiveProps(newProps) {
    this.highlight(newProps);
}
highlight(props) {        
    parseElement.innerHTML = props.code;        
    hljs.highlightBlock(parseElement);
    this.setState({
        code: {__html: parseElement.innerHTML}
    });
}

然后在render方法中渲染出新的已經格式化的代碼:

return (
   <pre><code dangerouslySetInnerHTML={this.state.code} /></pre>
);

這是一個JS小提琴

這仍然不是理想的,但是它沒有違反React原則,同時仍然使用Highlight.js依賴其他DOM操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM