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