简体   繁体   中英

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

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.

What is the appropriate react way of handling this?

Its because every new function defined its own this value.

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:

homeVideo.onended = () => {
   console.log(this.state);
   this.setState({ showVideo: !this.state.showVideo });
}

Arrow functions lexically binds the this value.

You don't need 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM