将网络音频上下文事件绑定回反应组件
bind web audio context event back to react component
我正在使用网络音频构建一个小型音频播放器 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"?
请考虑此方法在您的 class 组件中。
将回调函数更改为箭头函数
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;
}
}
我正在使用网络音频构建一个小型音频播放器 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"?
请考虑此方法在您的 class 组件中。
将回调函数更改为箭头函数
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;
}
}