简体   繁体   English

将 arguments 传递给反应中的事件处理程序

[英]Passing arguments to event handlers in react

So, I've been trying to learn React and came across this piece of code.所以,我一直在尝试学习 React 并遇到了这段代码。

 <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? deleteRow 怎么会有两个 arguments? It is only supposed to have one.它应该只有一个。 What does putting the 'e' into it do and why is it needed?将“e”放入其中有什么作用,为什么需要它? Why is id the first argument in the first line but the second argument in the second line?为什么 id 是第一行的第一个参数,而第二行的第二个参数? Why do we need to use 'bind' or 'this.'为什么我们需要使用'bind'或'this'。 with deleteRow at all?用 deleteRow 吗? I thought it was a built-in function.我以为是内置的function。

e is the event that is passed to the handler, but you can also pass other parameters. e是传递给处理程序的事件,但您也可以传递其他参数。

// 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如果您不指定,onClick 将自动传递事件

const deleteItem = (event) => {
     console.log(event)
}
<button onClick={deleteItem}>Delete Item</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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