【问题标题】:Force a React component to re-render despite a modified DOM尽管修改了 DOM,但强制 React 组件重新渲染
【发布时间】:2018-02-06 21:49:43
【问题描述】:

除了 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>
    )
  }

}

我试图从道具转移到状态,componentWillReceiveProps()componentDidUpdate()this.forceUpdate();,但没有成功。突出显示的代码保持不变,就好像道具没有改变一样。删除 Prism.js 解决了这个问题,并且组件更新正常。

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

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    还没有尝试过,但我会尝试使用 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>
        )
      }
    }
    

    【讨论】:

    • 我试过了,还是一样的问题。组件在初始化时确实有语法高亮显示,但是 - 当 props 更改时 - 不会再次渲染 Prism.js 修改的 DOM 部分。
    • 如果你把它包装在一个超时里怎么办:setTimeout(() => Prism.highlightElement(this.el), 0)
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2022-11-20
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    相关资源
    最近更新 更多