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>
I don't understand why the arrow function is required - why can't I just have the alert() on its own?
The docs state:
Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…