[英]Reactjs function binding on event handler
I'm trying to understand why we have to bind an object null to the function 我试图理解为什么我们必须将对象null绑定到函数
add(text) {
this.setState(prevState=> ({
notes: [
...prevState.notes,
{
id: this.nextId(),
note: text
}
]
}))
}
render() {
return (
<div className="board">
{this.state.notes.map(this.eachNote)}
<button onClick={this.add.bind(null, "New Note")}
id="add">Add note</button>
</div>
)
}
Why can't we just do this.add("New Note")
? 为什么我们不能这样做
this.add("New Note")
?
onClick={this.add("New Note")}
would immediately run the add()
method, then set the result as onClick
. onClick={this.add("New Note")}
会立即运行add()
方法,然后将结果设置为onClick
。 The result of add()
is undefined, because it doesn't return anything. add()
的结果是未定义的,因为它不返回任何内容。 So we'd essentially do onClick={undefined}
. 所以我们基本上做
onClick={undefined}
。
So to fix that, we can use an anonymous function: onClick={() => this.add("New Note")}
所以要解决这个问题,我们可以使用匿名函数:
onClick={() => this.add("New Note")}
This time, the program properly calls this.add("New Note")
when the button is clicked. 这次,程序在单击按钮时正确调用
this.add("New Note")
。
Or we can just take advantage of the fact that bind()
allows us to state the this
context and the arguments we want to pass, and simply use onClick={this.add.bind(this, "New Note")}
(using this
as first argument binds the instance as context, just like the arrow function in the 2nd paragraph) 或者我们可以利用
bind()
允许我们声明this
上下文和我们想要传递的参数的事实,并简单地使用onClick={this.add.bind(this, "New Note")}
(使用this
作为第一个参数将实例绑定为上下文,就像第2段中的箭头函数一样)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.