[英]How can I set the state of a component on video end in react?
In my component I have an componentDidUpdate
function where I play a video and on that video I set the video.onended
event as noted HERE 在我的组件我有一个
componentDidUpdate
功能,我播放视频并在该视频中,我设定的video.onended
事件作为注意到这里
Currently my code looks like this: 目前,我的代码如下所示:
componentDidUpdate: function() {
if(this.state.showVideo){
this.refs.homeVideo.play();
// Triggering event on video end
let homeVideo = document.getElementById("homeVideo");
homeVideo.onended = function(){
console.log(this.state);
this.setState({ showVideo: !this.state.showVideo });
}
}
}
My issue right now is that this.state is undefined in the onended function and so is setState, which is preventing me from updating the state of the component in react so that I can close the video player when it ends. 我现在的问题是onstate函数中未定义this.state,setState也未定义,这使我无法在react中更新组件的状态,以便我可以在视频播放器结束时关闭它。
What is the appropriate react way of handling this? 处理此问题的适当反应方式是什么?
Its because every new function defined its own this
value. 这是因为每个新函数都定义了自己的
this
值。
You can do something like: 您可以执行以下操作:
var self = this;
homeVideo.onended = function(){
console.log(self.state);
self.setState({ showVideo: !self.state.showVideo });
}
Or better yet, use arrow functions if your using ES6: 或者更好的是,如果您使用的是ES6,请使用箭头功能:
homeVideo.onended = () => {
console.log(this.state);
this.setState({ showVideo: !this.state.showVideo });
}
Arrow functions lexically binds the this
value. 箭头函数按词法绑定
this
值。
You don't need document.getElementById. 您不需要document.getElementById。
Try to update your code to this: 尝试将代码更新为此:
componentDidUpdate: function() {
var self = this;
if(this.state.showVideo){
let video = this.refs.homeVideo;
video.play();
video.onended = function(){
console.log(self.state);
self.setState({ showVideo: !self.state.showVideo });
}
}
}
JSfiddle example https://jsfiddle.net/ntfjncuf/ JSfiddle示例https://jsfiddle.net/ntfjncuf/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.