ReactJs:定义事件处理程序的最佳实践

ReactJs: Best Practice of defining event handlers

我最近开始使用 ReactJs,我想知道在 React 中定义事件处理程序的最佳实践是什么。这就是我一直在使用反应事件处理程序的方式:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0);
  const handleButtonClick = () => {
    setCounter(counter + 1);
  };
  return (
    <div className="App">
      <button onClick={() => handleButtonClick()}> 
        Click Me To increase counter
      </button>
      <div>
        <h4>Counter value is: </h4>
        {counter}
      </div>
    </div>
  );
}

我也听到过反对这种逻辑的争论。有人说最好在组件定义之外定义事件处理程序(App 在我们的例子中)。这样,它变得清晰、干净和简洁,而不是在组件内部创建混乱的多个函数(事件处理程序或非事件处理程序)。例如:

import React, { useState } from "react";
import "./styles.css";

const handleButtonClick = (setCounter, counter) => () => {
  setCounter(counter+1);
};

export default function App() {
  const [counter, setCounter] = useState(0);
  return (
    <div className="App">
      <button onClick={handleButtonClick(setCounter, counter)}> 
        Click Me To increase counter
      </button>
      <div>
        <h4>Counter value is: </h4>
        {counter}
      </div>
    </div>
  );
}

CodeSandbox Link for second approach 我想知道定义函数的最佳实践是什么?事件处理程序是否也应该在函数组件之上全局定义(App Component in this case)?

Should event handlers be also defined globally above the function component?

没有。

在组件外部定义事件处理程序,修改组件的状态 中断 cohesion

组件内的事件处理程序解释组件的不同交互。拥有一个“包装器”处理程序只会破坏 single level of abstraction.

我的两分钱。

您不需要在 onClick 中创建额外的函数。只是不要打电话给它。 onClick触发时调用onClick方法

const handleButtonClick = () => {
  setCounter(counter + 1);
};  // return function

<div onClick={handleButtonClick} />
// it will be call the handleButtonClick
// when onClick is trigger


import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0);
  const handleButtonClick = () => {
    setCounter(counter + 1);
  };
  return (
    <div className="App">
      <button onClick={handleButtonClick}> 
        Click Me To increase counter
      </button>
      <div>
        <h4>Counter value is: </h4>
        {counter}
      </div>
    </div>
  );
}