reactjs - 将网络音频上下文事件绑定回反应组件
问题描述
我正在使用 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”?
解决方案
考虑这个方法在你的类组件中。
将回调函数更改为箭头函数
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;
}
}
推荐阅读
- python - 获取库存数据问题
- swift - 如何在同一个 IBAction 中取消选择(取消突出显示)按钮
- php - 不工作使用 file_get_contents 发布数据
- github - 将使用 noreply 电子邮件更改我的 GitHub 用户名更新/删除属性
- lua - 如何在 Lua 表中查找 Corona SDK 显示对象的所有条目?
- google-maps - 我们可以在 void initState() 中插入两个方法吗?
- r - 绑定包含嵌套 data.frames 列的 r data.frames
- php - 使用硬链接时,如何防止同一文件被包含两次?
- postgresql - PostgreSQL按天分组时间戳
- rust - 为什么除了 Ord 特征之外,Rust 还需要 PartialOrd 特征?