我是React的初学者。在学习React时,有时我看到人们在事件监听器中使用匿名函数,我想知道下面的代码是否相同。我认为,要调用函数onDelete,我们只需要使用onClick = {this.onDelete(id)}
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={()=>{this.onDelete(bookCart._id)}}>Delete</Button>
)
},this;
和
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={this.onDelete(bookCart._id)}>Delete</Button>
)
},this;
需要传递参数时,可以使用箭头功能。
如果在函数中加上括号,则实际上是在执行该函数。
因此,使用以下代码:
<Button onClick={ this.onDelete(bookCart._id) }>Delete</Button>
...您设置的onClick到结果的this.onDelete(bookCart._id)
如果使用这样的箭头功能:
<Button onClick={ () => this.onDelete(bookCart._id) }>Delete</Button>
...然后将onClick设置为一个函数,该函数在执行时将this.onDelete
使用参数进行调用。
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句