我是 React 初学者。在学习React的过程中,有时会看到有人在事件监听器中使用匿名函数,不知道下面的代码是不是一样。我认为,要调用函数 onDelete,我们只需要使用 onClick={this.onDelete(id)}
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={()=>{this.onDelete(bookCart._id)}}>Delete</Button>
)
},this;
Run Code Online (Sandbox Code Playgroud)
和
const cartItem=this.props.cart.map((bookCart)=>{
return (
<Button onClick={this.onDelete(bookCart._id)}>Delete</Button>
)
},this;
Run Code Online (Sandbox Code Playgroud)
当您需要传递参数时,您可以使用箭头函数。
如果您在函数中添加括号,您实际上是在执行该函数。
因此,使用此代码:
<Button onClick={ this.onDelete(bookCart._id) }>Delete</Button>
Run Code Online (Sandbox Code Playgroud)
...您设置的onClick到结果的this.onDelete(bookCart._id)
如果您使用这样的箭头函数:
<Button onClick={ () => this.onDelete(bookCart._id) }>Delete</Button>
Run Code Online (Sandbox Code Playgroud)
...然后您将onClick设置为一个函数,该函数在执行时将this.onDelete使用参数调用。
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
742 次 |
| 最近记录: |