簡體   English   中英

React-組件更新后如何獲取真實的DOM元素

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

我正在嘗試在組件渲染后運行一個函數。

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

在此函數中,我需要使用document.getElementById("myId")獲得一個真正的DOM元素。

所以我試圖在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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM