React-如何与事件处理程序一起使用bind并保留事件对象

React - How to use bind with an event handler and preserve event object?

本文关键字:bind 保留 对象 事件 一起 事件处理 程序 React-      更新时间:2023-09-26

我有一些东西:

<IconButton
  icon="icon-delete"
  onClick={this.deleteItem.bind(this, itemName)}
/>

但是,当deleteItem函数触发时,event参数将丢失。提及this仅指React组件。使用bind时,如何保留/传递event

this.deleteItem.bind(this, itemName)表示itemName的值将被分配给this.deleteItem的第一个参数。

因此,事件对象将被分配给第二个参数

有关.bind的更多信息,请参阅MDN文档。

ES6语法中的

。您可以使用::this.deleteItem

// This is binding the function onFormSubmit to this fn.bind(this)
<form onSubmit={::this.onFormSubmit}>
</form>

我这里有一些和你一样的代码。

<button className="removeitem" onClick={this.handleClickRemoveFromCart(item, item.id)}>
   <i className="icon icon-close -x3" />
</button>

handleClickRemoveFromCart(item, id) {
    return this.props.onRemoveFromCart(item, id);
};