简体   繁体   中英

React onClick - pass event with parameter

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?

Try this:

<button 
   onClick={(e) => {
      this.clickMe(e, someParameter);
   }}
>
Click Me!
</button>

And in your function:

function clickMe(event, someParameter){
     //do with event
}

With the ES6, you can do in a shorter way like this:

const clickMe = (parameter) => (event) => {
    // Do something
}

And use it:

<button onClick={clickMe(someParameter)} />

Solution 1

function clickMe(parameter, event){
}

<button onClick={(event) => {this.clickMe(someparameter, event)}></button>

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

function clickMe(parameter, event){
}

<button onClick={this.clickMe.bind(this, someParameter)}></button>

Currying with ES6 example:

const clickHandler = param => event => {
  console.log(param); // your parameter
  console.log(event.type); // event type, e.g.: click, etc.
};

Our button, that toggles handler:

<button onClick={(e) => clickHandler(1)(e)}>Click me!</button>

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 use event.persist() :

const clickHandler = param => event => {
  event.persist();
  console.log(event.target);
  setTimeout(() => console.log(event.target), 1000); // won't be null, otherwise if you haven't used event.persist() it would be null.
};

Here's live example: https://codesandbox.io/s/compassionate-joliot-4eblc?fontsize=14&hidenavigation=1&theme=dark

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,

const handleBtnClick = e => {
  const { id } = JSON.parse(e.target.dataset.onclickparam);
  // ...
};

<button onClick={handleBtnClick} data-onclickparam={JSON.stringify({ id: 0 })}>

See https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes for using data-* attributes.

<Button onClick={(e)=>(console.log(e)}>Click Me</Button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM