首页 > 解决方案 > 将网络音频上下文事件绑定回反应组件

问题描述

我正在使用 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”?

标签: reactjsweb-audio-api

解决方案


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

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

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

推荐阅读