首页 > 解决方案 > 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>
  );
}

标签: javascriptreactjsfunctioneventsreact-hooks

解决方案


如果您不使用箭头函数,则无论单击按钮如何,该函数都会在 render() 上执行。这就是您设置箭头功能以防止这种行为的原因。在您每次渲染的情况下,如果您不使用箭头函数语法,计数器将会增加


推荐阅读