为什么需要将匿名函数传递给onClick事件? [英] Why do I need to pass an anonymous function into the onClick event?
问题描述
我一直在尝试学习React的基础知识.但是,我遇到了本教程中的一节,要求我将 alert()
放置在onClick事件中,例如:
I've been trying to learn the basics of React. However, I've come across a section in the tutorial that asks me to place an alert()
inside of an onClick event as such:
<button className="square" onClick={() => {alert("click");}}>
{this.state.value}
</button>
我不明白为什么需要箭头功能-为什么我不能仅仅拥有alert()?
I don't understand why the arrow function is required - why can't I just have the alert() on its own?
文档状态:
忘记()=>并编写onClick = {alert('click')}是一个常见错误,每次组件重新渲染时都会触发警报.
Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.
哪个是正确的-我已经尝试过了,它确实会不断调用 alert()
.但为什么?它不是应该在onClick而不是在render上触发吗?匿名函数做什么才能阻止这种行为?
Which is correct - I've tried this, and it does continually call alert()
. But why? Isn't it supposed to fire onClick, and not on render? What does the anonymous function do that stops this behaviour?
推荐答案
因为如果调用一个函数,则该函数将运行.(然后您从中获得返回值)
Because if you call a function, then the function runs. (And you get the return value from it)
const onClick = alert("hello");
console.log(onClick);
如果您定义一个调用函数(Y)的函数(X),那么直到您调用X时,它才调用Y.
If you define a function (X) that calls a function (Y), then it doesn't call Y until you call X.
const onClick = () => alert("hello");
console.log(onClick);
这篇关于为什么需要将匿名函数传递给onClick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!