[英]Pass prop value as a parameter in an arrow function in an event handler onClick() in React
[英]How to pass an onClick event handler a function that takes a parameter and still bind the function to the component's “this” context?
我有一个基于类的React组件,名为“ AllProducts.jsx”,我将其定义为“ AllProducts扩展组件”,因此,当我将函数传递给onClick事件处理程序时,我需要绑定“ this”的上下文,但是当我尝试将这些函数之一传递给参数,我在控制台中收到一条错误消息,提示“无法读取未定义的属性绑定”。
这是代码抛出错误时的样子,请查看i标记的onClick处理程序:
renderProductInfo() {
return this.props.allProducts.map((product) => {
return [
<li id="shownName">{product.name}</li>,
<li id="shownSKU">{product._id}</li>,
<li id="shownCategory">{product.category}</li>,
<li id="shownPrice">${product.price}</li>,
<li id="shownQuantity">{product.quantity}</li>,
<i onClick={this.handleEditProduct(product._id).bind(this)}
id="shownEdit" className="fi-pencil"></i>,
<br />
];
});
}
我通过像这样在onClick处理程序内定义函数来解决此问题:
<i onClick={() => {
this.props.fetchSingleProduct(product._id).then(() => {
var opposite = !this.state.editProduct;
this.setState({
editProduct: opposite
});
});
}}
id="shownEdit" className="fi-pencil"></i>
有没有办法让我直接传递参数并避免错误?
通常,这是使用箭头函数传递参数的方式:
<i onClick={() => this.handleEditProduct(product._id)} id="shownEdit" className="fi-pencil"></i>
另外,这就是使用.bind
:
<i onClick={this.handleEditProduct.bind(this, product._id)} id="shownEdit" className="fi-pencil"></i>
您需要在函数上调用.bind
,而不是函数调用的返回值。 因此,任何参数都将放在上下文之后(第一个参数)。
这正在调用该函数,从而导致错误:
onClick={this.handleEditProduct(product._id).bind(this)}
这是将函数与参数绑定在一起,这是您想要的:
onClick={this.handleEditProduct.bind(this, product._id)}
请注意, handleEditProduct
的功能签名应为(productId, event)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.