简体   繁体   中英

Passing arguments to event handlers in react

So, I've been trying to learn React and came across this piece of code.

 <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

This baffles me. How can deleteRow have two arguments? It is only supposed to have one. What does putting the 'e' into it do and why is it needed? Why is id the first argument in the first line but the second argument in the second line? Why do we need to use 'bind' or 'this.' with deleteRow at all? I thought it was a built-in function.

e is the event that is passed to the handler, but you can also pass other parameters.

// handlers
const deleteRow = (e, someVal) => {
   console.log(e);
   console.log(someVal); // "another value"
}

const deleteRow = (e) => {
   console.log(e); // still get the event
}

<button onClick={(e) => this.deleteRow(e, "another value")}>Delete Row</button>

// if you don't need to pass other arguments, you can even do
<button onClick={this.deleteRowB}>Delete Row</button>

Yes, that can be misleading

The onClick would pass the event automatically if you don't specify

const deleteItem = (event) => {
     console.log(event)
}
<button onClick={deleteItem}>Delete Item</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