如何在react中设置视频端组件的状态

How can I set the state of a component on video end in react?

本文关键字:组件 状态 视频 设置 react      更新时间:2023-09-26

在我的组件中,我有一个componentDidUpdate函数,我在其中播放视频,并在该视频上设置video.onended事件,如HERE 所示

目前我的代码如下:

  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 });
      }
    }
  }

我现在的问题是,这个.state在onended函数中是未定义的,setState也是,这阻止了我更新react中组件的状态,以便在视频播放器结束时关闭它。

处理此问题的适当反应方式是什么?

您不需要document.getElementById.

尝试将您的代码更新为:

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示例https://jsfiddle.net/ntfjncuf/

因为每个新函数都定义了自己的this值。

你可以做一些类似的事情:

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

或者更好的是,如果您使用ES6:,请使用箭头功能

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

Arrow函数在词汇上绑定this值。