首页 > 解决方案 > 在 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() 来使音频正常工作,但我觉得有一种我不知道的更清洁的方式。

标签: reactjs

解决方案


您可以替换onClick为以下内容

onClick={this.playSound}

推荐阅读