React - 如何在组件更新后获取真正的 DOM 元素

React - how to get real DOM element after component is updated

本文关键字:获取 元素 DOM 更新 组件 React      更新时间:2023-09-26

我正在尝试在反应组件渲染后运行一个函数。

render: function(){
   return(
      <div id="myId"></div>
   )
}

在这个函数中,我需要得到一个真正的 DOM 元素,document.getElementById("myId")

所以我尝试在componentDidUpdate中运行我的函数,但显然我没有在浏览器"绘制"我的div 之前运行,所以我得到了null.

这个问题

有优雅的解决方案吗?

你假设在调用 componentDidUpdate 方法时不一定绘制 DOM 元素是对的。

您可以使用 window.requestAnimationFrame 绕过此操作。

onNextFrame() {
  var _this = this;
  window.requestAnimationFrame(function() {
    var domnode = _this.getDOMNode();
    if (domnode !== undefined) {
      // set your attributes here
      jwplayer(domnode).setup({
        "file": "http://example.com/myVideo.mp4",
        "image": "http://example.com/myImage.png",
        "height": 360,
        "width": 640
      });
    }
  });
},
componentDidMount() {
  this.onNextFrame();
},
componentDidUpdate() {
  this.onNextFrame();
}