javascript - react中的事件处理:什么情况下需要对事件使用箭头函数,什么时候只需要传递类方法(函数)?
问题描述
例子:
1)
<button onClick="{this.handleClick}">
Click me
</button>
<button onClick={() => this.handleClick()}>
为什么在这里我们不能只传递一个函数?我的意思是为什么我们需要一个箭头函数。
import React, { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>you clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>click me</button>
</div>
);
}
解决方案
如果您不使用箭头函数,则无论单击按钮如何,该函数都会在 render() 上执行。这就是您设置箭头功能以防止这种行为的原因。在您每次渲染的情况下,如果您不使用箭头函数语法,计数器将会增加
推荐阅读
- ios - 自定义字体在 Storyboard 中不可用 - Xcode
- ruby-on-rails - 表 Transaction 和 User - Ruby on Rails 应该使用什么样的关系?
- javascript - 从 base64 图像中获取 mime 和 ext
- node.js - Mongodb发现不打印json数据
- c++ - 使用 QEMU 进行机器级指令跟踪监控?
- bitbucket - 如何将 Hybris Custom 和 Config 文件夹集成到本地安装?
- regex - htaccess 重定向到具有相同域扩展名的另一个子域
- pyspark - 如何使用折叠或映射函数在 Pyspark 中投射多个列?
- python - 如何创建一个元素列表,其中开始索引在一个列表中给出,直到我遇到较大列表中的特定元素?
- javascript - 如何使用防止 Javascript 的默认事件?