[英]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.