[英]Force a React component to re-render despite a modified DOM
除了React,我還使用一個名為Prism.js的外部庫來突出顯示語法。 我有一個React組件,可以生成一些示例代碼。 第一次渲染很好。 該組件使用其初始道具進行渲染,然后調用Prism.highlightElement();
在componentDidUpdate()
中,語法突出顯示也很好。 但是,我們在React父組件中輸入了內容,這些內容更改了需要生成的代碼的內容。 進行更改后,生成的突出顯示的代碼保持不變。 子組件的其他未語法突出顯示的部分認為Prism.js確實可以很好地更新。 因此,React不重新呈現修改后的DOM似乎是一個問題。
這是子組件的簡化版本:
class CodeExample extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps(newProps) {
this.forceUpdate();
if(document.getElementById('integrationExample')) {
Prism.highlightElement(document.getElementById('integrationExample'));
}
}
componentDidUpdate() {
if(document.getElementById('integrationExample')) {
Prism.highlightElement(document.getElementById('integrationExample'));
}
}
render() {
return (
<div>
<pre>
<code className="language-bash" id="integrationExample">$ curl {this.props.resultsUrl}
</code>
</pre>
</div>
)
}
}
我已經嘗試從props, componentWillReceiveProps()
, componentDidUpdate()
, this.forceUpdate();
轉移到狀態this.forceUpdate();
沒有成功。 高亮顯示的代碼保持不變,好像道具沒有變化。 刪除Prism.js可解決此問題,並且組件更新正常。
有什么想法可以在保留Prism.js的同時強制重新渲染代碼示例?
還沒有嘗試過,但是我將使用componentDidMount
和componentDidUpdate
嘗試一下,看看如何使用ref
而不是document.getElementById
。
class CodeExample extends React.Component {
highlight(){
Prism.highlightElement(this.el);
}
componentDidMount(){
this.highlight();
}
componentDidUpdate(){
this.highlight();
}
render() {
return (
<div>
<pre>
<code className="language-bash" ref={el => this.el = el}>$ curl {this.props.resultsUrl}
</code>
</pre>
</div>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.