【问题标题】:bind web audio context event back to react component将网络音频上下文事件绑定回反应组件
【发布时间】:2019-03-31 16:55:42
【问题描述】:

我正在使用 Web Audio API 构建一个小的音频播放器。

我有一个播放按钮,根据内容是播放还是停止显示不同的样式。

但我不确定如何将音频上下文的事件绑定回组件,以便设置按钮的状态。

 play = () => {
     if(audioCtx.state === 'running' && this.state.started) {
      audioCtx.suspend().then(function() {

        //HERE IS WHERE I WANT TO SET STATE buttonOn
       //but the "this" is not recognized

      });
    } else if(audioCtx.state === 'suspended') {
      audioCtx.resume().then(function() {
        this.setState({buttonOn = true});  <== "this" not recognized
      });
    } else {
      this.playNext(0);
      this.setState({started: true});
      buttonOn = true;
    }
  }

如何从这些事件中回到组件的“this”?

【问题讨论】:

    标签: reactjs web-audio-api


    【解决方案1】:

    考虑这个方法在你的类组件中。

    将回调函数更改为箭头函数

     play = () => {
         if(audioCtx.state === 'running' && this.state.started) {
          audioCtx.suspend().then(() => {
    
          });
        } else if(audioCtx.state === 'suspended') {
          audioCtx.resume().then(() => {
            this.setState({buttonOn: true});
          });
        } else {
          this.playNext(0);
          this.setState({started: true});
          buttonOn = true;
        }
      }
    

    【讨论】:

    • 这不起作用。它什么也没做。我在组件外部定义了 audioCtx。这有关系吗?
    • play 方法定义在哪里?你能在codesandbox 上做一个简单的工作示例吗?
    • 我的错。您的解决方案有效。我忘记重置样式了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多