简体   繁体   English

自动调用在onClick JSX事件中对此this.function()进行响应而不会出现错误

[英]auto call react this.function() in a onClick JSX event without getting an error

I have a function that I want to run which plays a particular audio file when the screen loads and when the onClick is clicked by the user. 我具有要运行的功能,该功能在屏幕加载时以及用户单击onClick时播放特定的音频文件。

playSound = () => {
    let audioSound = new Audio(this.state.activity[this.state.index].audio0);
    return audioSound.play();
}

I want it to run onload, so I included the parentheses in front of the onClick function call. 我希望它在onload上运行,因此我在onClick函数调用的前面加上了括号。

onClick={this.playSound()}

The only problem with this is that I get this error in the console when it loads or I click on the onClick again. 唯一的问题是加载控制台时,我在控制台中收到此错误,或者再次单击onClick。

Warning: Expected `onClick` listener to be a function, instead got a value of `object` type

I'd like to know why this specific error is popping up. 我想知道为什么会弹出此特定错误。

I'm able to get the audio working by calling the this.playSound() inside of my render(), but I feel like there's a cleaner way that I don't know about. 我可以通过在render()内部调用this.playSound()来使音频正常工作,但是我感觉有一种我不知道的更干净的方式。

您可以将onClick替换为以下内容

onClick={this.playSound}

If you want to run the playSound function any time the element is clicked, you have to change it to onClick={this.playSound} as other people have suggested. 如果您想在onClick={this.playSound}单击元素时运行playSound函数,则必须像其他人建议的那样将其更改为onClick={this.playSound}

It sounds like you also want playSound to run when the component loads for the first time? 听起来您希望在首次加载组件时运行playSound If so, add this.playSound() inside the lifecycle method componentDidMount . 如果是这样,请在生命周期方法componentDidMount添加this.playSound() This would mean your component has to be a class-based stateful component, not a functional stateless component. 这意味着您的组件必须是基于类的有状态组件,而不是功能性的无状态组件。 You mentioned a render method in your question, which makes me believe your component is already class-based. 您在问题中提到了render方法,这使我相信您的组件已经基于类。 Here is how this lifecycle method would look like for you: 这就是您的生命周期方法的样子:

componentDidMount() {
    this.playSound();
}

If you want playSound to run every time any state or props change in your component (which seems unlikely), you could put this.playSound() at the beginning of your render method. 如果您希望playSound每次在组件中的任何状态或道具发生更改时都运行(这似乎不太可能),则可以将this.playSound()放在render方法的开头。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM