reactjs - 在 onClick JSX 事件中自动调用 react this.function() 而不会出错
问题描述
我有一个要运行的函数,它在屏幕加载和用户单击 onClick 时播放特定的音频文件。
playSound = () => {
let audioSound = new Audio(this.state.activity[this.state.index].audio0);
return audioSound.play();
}
我希望它运行 onload,所以我在 onClick 函数调用前面加上了括号。
onClick={this.playSound()}
唯一的问题是我在控制台加载时收到此错误,或者我再次单击 onClick。
Warning: Expected `onClick` listener to be a function, instead got a value of `object` type
我想知道为什么会弹出这个特定的错误。
我可以通过在我的 render() 中调用 this.playSound() 来使音频正常工作,但我觉得有一种我不知道的更清洁的方式。
解决方案
您可以替换onClick
为以下内容
onClick={this.playSound}
推荐阅读
- c - printf()函数的实现
- r - 时间戳上的 R 子集 data.frame
- python - 将两个 Pandas Dataframes 转换为每个组的元组字典
- r - Tidycensus 包:你能用人口普查块获得经纬度吗?
- docker - 无法构建 docker 容器
- java - 如何在 Micronaut 中使用 @Parameter?
- twitter - MVC 5 不能让 Twitter Auth 工作了
- javascript - 在数字前加上 + 或 -
- autohotkey - 了解为什么我的 AutoHotkey 变量没有被分配
- reactjs - 如何安全地传递参数以使用 react-rails 反应组件