Without Parameter
function clickMe(e){
//e is the event
}
<button onClick={this.clickMe}></button>
With Parameter
function clickMe(parameter){
//how to get the "e" ?
}
<button onClick={() => this.clickMe(someparameter)}></button>
I want to get the event
. How can I get it?
With the ES6, you can do in a shorter way like this:
And use it:
Try this:
And in your function:
Solution 1
Solution 2
Using the bind function is considered better, than the arrow function way, in solution 1.
Note, that the event parameter should be the last parameter in the handler function
To solve the creating new callback issue completely, utilize the
data-*
attributes in HTML5 is the best solution IMO.Since in the end of the day, even if you extract a sub-component to pass the parameters, it still creates new functions.
For example,
See https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes for using
data-*
attributes.Currying with ES6 example:
Our button, that toggles handler:
If you want to call this function expression without an event object, then you’d call it this way:
clickHandler(1)();
Also, since react uses synthetic events (a wrapper for native events), there’s an event pooling thing, which means, if you want to use your
event
object asynchronously, then you’d have to useevent.persist()
:Here’s live example: https://codesandbox.io/s/compassionate-joliot-4eblc?fontsize=14&hidenavigation=1&theme=dark
<Button onClick={(e)=>func(e, argument)}>Click Me