Reactjs 在onClick JSX事件中自动调用react this.function(),而不会出现错误
我有一个我想要运行的函数,在屏幕加载和用户单击onClick时播放特定的音频文件Reactjs 在onClick JSX事件中自动调用react this.function(),而不会出现错误,reactjs,Reactjs,我有一个我想要运行的函数,在屏幕加载和用户单击onClick时播放特定的音频文件 playSound = () => { let audioSound = new Audio(this.state.activity[this.state.index].audio0); return audioSound.play(); } 我希望它运行onload,所以我在onClick函数调用前面加了括号 onClick={this.playSound()} 唯一的问题是,当控制台加
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}
您可以将
onClick
替换为以下内容
onClick={this.playSound}
如果您想在任何时候单击元素时运行
playSound
函数,则必须按照其他人的建议将其更改为onClick={this.playSound}
听起来您还想在组件首次加载时运行playSound
?如果是这样,请将this.playSound()
添加到生命周期方法componentDidMount
中。这意味着您的组件必须是基于类的有状态组件,而不是功能性无状态组件。您在问题中提到了render
方法,这让我相信您的组件已经基于类了。以下是此生命周期方法的外观:
componentDidMount() {
this.playSound();
}
如果希望playSound
在组件中的任何状态或道具每次更改时运行(这似乎不太可能),可以将this.playSound()
放在render
方法的开头
希望这有帮助 如果您想在任何时候单击元素时运行
playSound
函数,您必须按照其他人的建议将其更改为onClick={this.playSound}
听起来您还想在组件首次加载时运行playSound
?如果是这样,请将this.playSound()
添加到生命周期方法componentDidMount
中。这意味着您的组件必须是基于类的有状态组件,而不是功能性无状态组件。您在问题中提到了render
方法,这让我相信您的组件已经基于类了。以下是此生命周期方法的外观:
componentDidMount() {
this.playSound();
}
如果希望playSound
在组件中的任何状态或道具每次更改时运行(这似乎不太可能),可以将this.playSound()
放在render
方法的开头
希望这有帮助 只需将onClick={this.playSound()}替换为onClick={this.playSound}只需将onClick={this.playSound()}替换为onClick={this.playSound}