I'm confused by this when doing event handling in javascript with ReactJS.
Is there any differences between
<button onClick={f()} />
and
<button onClick={()=>f()} />
what I know is the second one is a wrapping function that return f(), but i don't see what exactly changed there. And I do see both of them in others' code.
In your example, the first case just calls f
at load time, which is probably not what you want unless f
returns another function (which would be called when a click event occurs). The second is just an anonymous function wrapping f
so that f
is not called until the click
event happens.
Why is the second notation useful?
If f
takes no arguments then using
<button onClick={ f } /> // note: no parentheses
and
<button onClick={ () => f() } />
are pretty much equivalent. There is a slight difference between the two in that the event
is passed to f
in the first case and is not in the second. Technically <button onClick={ event => f(event) }/>
would be equivalent to the first case, but this is somewhat beside the point.
However, if f
does take some arguments (other than the event
itself), then it's useful to use:
<button onClick={ () => f(someValue) } />
so that someValue
can be passed to f
when the click event happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With