Javascript 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件';s";这";上下文
我有一个名为“AllProducts.jsx”的基于类的React组件,我将其定义为“class AllProducts Extendes component”,因此当我将函数传递给onClick事件处理程序时,我需要绑定“this”的上下文,但当我尝试向其中一个函数传递参数时,控制台中会出现一个错误,即“无法读取未定义的属性绑定。” 这是代码抛出错误时的样子,请查看i标记的onClick处理程序:Javascript 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件';s";这";上下文,javascript,reactjs,Javascript,Reactjs,我有一个名为“AllProducts.jsx”的基于类的React组件,我将其定义为“class AllProducts Extendes component”,因此当我将函数传递给onClick事件处理程序时,我需要绑定“this”的上下文,但当我尝试向其中一个函数传递参数时,控制台中会出现一个错误,即“无法读取未定义的属性绑定。” 这是代码抛出错误时的样子,请查看i标记的onClick处理程序: renderProductInfo() { return this.props.all
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 />
];
});
}
renderProductInfo(){
返回此.props.allProducts.map((产品)=>{
返回[
{product.name} ,
{product.\u id} ,
{product.category} ,
${product.price} ,
{product.quantity} ,
,
];
});
}
我通过在onClick处理程序中定义函数来解决这个问题,如下所示:
<i onClick={() => {
this.props.fetchSingleProduct(product._id).then(() => {
var opposite = !this.state.editProduct;
this.setState({
editProduct: opposite
});
});
}}
id="shownEdit" className="fi-pencil"></i>
{
this.props.fetchSingleProduct(product.u id).然后(()=>{
var反面=!this.state.editProduct;
这是我的国家({
编辑产品:反面
});
});
}}
id=“shownEdit”className=“fi pencil”>
有没有一种方法可以让我直接传入参数并避免错误?以下是您通常使用箭头函数传递参数的方式:
<i onClick={() => this.handleEditProduct(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)
,所以我是如何调用函数调用值的bind的,我不清楚这一点?this.handleEditProduct
=函数。this.handleEditProduct(product.\u id)
=正在调用的函数。当您将.bind
放在正在调用的函数上时,它会尝试调用返回的任何.handleEditProduct
(在本例中,未定义)哇,完全有道理。谢谢你的解释和回答!你说的函数签名是什么意思?我不熟悉这个术语。意思是函数所采用的参数:因为onClick
是一个事件处理程序,你会得到(事件)
作为参数,由于bind
预先添加了您提供的参数,您将获得(productId,event)
作为参数。因此,由于函数的签名,“event”将自动在第3位传递?是的,基本上…bind()
返回一个新函数,当调用该函数时,该函数将自动在您传递的附加参数前面加上前缀。因此,在本例中,由于onClick
是通过事件参数调用的,并且在调用函数时,您已将bind
与参数product.\u id
(假设
元素执行类似于this.props.onClick(event)
)的操作,您实际上得到了(productId,event)
。
onClick={this.handleEditProduct.bind(this, product._id)}