2
我是React新手,不確定處理以下情況的正確方法:如何處理React中的第三方dom操作?
我做了一個呈現代碼並使用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>
);
}
}
我的理解是,作出反應處理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?
謝謝,那就是我一直在尋找的! –