Reputation: 1
In my render() function , I want to run a function like this:
<a onClick={handleClickEdit(record.productId)}>Edit</a>
The function handleClickEdit(id) will be executed when component render , this is not what I want. I want to run handleClickEdit(id) when I click the Edit label. So , I tried a lot times, I found below style is worked well :
<a onClick={() =>handleClickEdit(record.productId)}>Edit</a>
What is the diffences between these code ? Plases help ,thanks a lot .
Upvotes: 0
Views: 44
Reputation: 2550
onClick
is a function that will be called whenever the component is clicked. The value assigned to it must be a function.
The expression () => myFunction(arg)
wraps myFunction
in an anonymous function; it is equivalent to:
function(){ return myFunction(arg); }
When the anonymous function is executed, myFunction
is called with arg
as an argument. Assigning the anonymous function to onClick
means that myFunction(arg)
will execute whenever the component is clicked. The value returned by myFunction
is irrelevant. This is what happens in the second (working) code snippet.
In the first code snippet, myFunction(arg)
is assigned directly to onClick
. But myFunction(arg)
is not a function — it is a function invocation; myFunction
is executed immediately with arg
as an argument, and the returned value gets assigned to onClick
. The returned value may not even be a function!
If you don't want to use the arrow notation / explicit wrapper-function, you could use:
onClick={ myFunction.bind(null, arg) }
You can read more about Function.prototype.bind
here; it returns a new function with arg
bound as the first argument. The first argument passed to bind
will be bound to the this
keyword during function execution.
Upvotes: 3