【问题标题】:How can I set the state of a component on video end in react?如何在反应中设置视频端组件的状态?
【发布时间】:2016-09-01 17:00:59
【问题描述】:

在我的组件中,我有一个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 中更新组件的状态,以便我可以在视频播放器结束时关闭它。

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

【问题讨论】:

    标签: javascript video reactjs html5-video


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-13
        • 1970-01-01
        • 2020-12-26
        • 2021-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多