gpt4 book ai didi

javascript - 尽管 DOM 已修改,仍强制 React 组件重新渲染

转载 作者:行者123 更新时间:2023-11-28 03:44:13 25 4
gpt4 key购买 nike

除了 React 之外,我还使用一个名为 Prism.js 的外部库来进行语法突出显示。我有一个 React 组件,可以生成一些示例代码。第一次渲染没问题。组件使用其初始属性进行渲染,然后我在 componentDidUpdate() 中调用 Prism.highlightElement(); ,它也可以很好地进行语法突出显示。但是,我们在 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(); 转移到状态,但没有成功。突出显示的代码保持不变,就好像 Prop 没有改变一样。删除 Prism.js 解决了该问题,并且组件更新正常。

有什么想法可以在保留 Prism.js 的同时强制代码示例重新渲染吗?

最佳答案

尚未尝试过此操作,但我会使用 componentDidMountcomponentDidUpdate 尝试此操作,并查看使用 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>
)
}
}

关于javascript - 尽管 DOM 已修改,仍强制 React 组件重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48652547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com