如何在反应中设置视频端组件的状态?

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

在我的组件中,我有一个 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 });
      }
    }
  }

我现在的问题是 this.state 在 onended 函数中未定义,setState 也是如此,这使我无法在 React 中更新组件的状态,以便我可以在视频播放器关闭时关闭它结束。

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

这是因为每个新函数都定义了自己的 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 });
}

箭头函数词法绑定 this 值。

你不需要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/