gpt4 book ai didi

reactjs - 为什么我们在 onClick 事件上使用 Bind 方法

转载 作者:行者123 更新时间:2023-12-03 13:42:33 25 4
gpt4 key购买 nike

我正在学习React.js。在教程中作者将onClick与bind一起使用,但在某些地方他没有将bind与onClick一起使用。我无法理解两者之间的区别。

 <button onClick={this.handleAdd}>Add Item</button>

最佳答案

您可以使用bind 来将某个参数传递给处理程序方法。

例如:

render: function() {
return _.map(list, function(item) {
return <li onClick={this.clickItem.bind(this, item)}>{item.name}</li>;
});
},
clickItem: function(item, event) {
//do something with the clicked item
}

如果您不需要注入(inject)参数,则不需要绑定(bind),因为react始终在组件范围内调用处理程序方法 - although this is changing soon

关于reactjs - 为什么我们在 onClick 事件上使用 Bind 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28688485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com