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

标签 reactjs

我正在学习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/

相关文章:

reactjs - 对象作为 React 子对象无效(发现 : object with keys {})

javascript - 插入 HTML 的 React 代码似乎不起作用

javascript - React-router-dom v6 显示除默认 URL 之外的空白页面

javascript - 开关的 React-Native ListView 不更新

css - 如何禁用除 iFrame 悬停之外的所有鼠标事件?

reactjs - 一个标签导航器中的多个屏幕

javascript - react : componentDidMount + setState not re-rendering the component

reactjs - react this.props 未定义或空对象

javascript - 通过API调用使用react redux进行文件上传

javascript - 打开lightBox后如何增加图像宽度?