首页 > 解决方案 > 返回callBack的onClick函数和直接放在onClick中的callBack有什么区别?

问题描述

我想创建一个反应组件,使扩展面板像这样https://material-ui.com/components/expansion-panels/我正在使用一个 materialUI 库。

    import React from "react";
    import { makeStyles } from "@material-ui/core/styles";
    import ExpansionPanel from "@material-ui/core/ExpansionPanel";
    import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
    import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
    import Typography from "@material-ui/core/Typography";
    import ExpandMoreIcon from "@material-ui/icons/ExpandMore";

    export default function ControlledExpansionPanels() {
      [...]
      const [expanded, setExpanded] = React.useState(false);

      const handleChange = panel => (event, isExpanded) => {
        setExpanded(isExpanded ? panel : false);
      };

      return (
        <>
          <ExpansionPanel
            expanded={expanded === "panel1"}
            onChange={handleChange("panel1")}
          >
            [...]
          </ExpansionPanel>
          <ExpansionPanel
            expanded={expanded === "panel2"}
            onChange={handleChange("panel2")}
          >
            [...]
          </ExpansionPanel>
        </>
      );
    }

他们的组件使用了一个 onChange 道具,该道具执行组件的函数 handleChange 以返回一个回调函数。

这种方法有什么区别:

   [...]
      const handleChange = (event, isExpanded, panel) => {
        setExpanded(isExpanded ? panel : false);
      };

      return (
        <>
          <ExpansionPanel
            expanded={expanded === "panel1"}
            onChange={(event, isExpanded) => handleChange(event, isExpended, "panel1")}
          >
            [...]

我想知道运行返回callBack的函数或将callBack直接放入onChange有什么区别?我的印象是,这是一个声明的匿名函数数量的优化问题,但据我了解,这段代码通过执行 handleChange 声明了一个匿名函数,因此为每个 onChange 创建了一个回调。

我想知道何时以及为什么应该使用每种解决方案。预先感谢您的澄清。

标签: reactjsreact-nativecallbackonclick

解决方案


你是对的,它与声明的匿名函数的数量有关。
以他们使用 handleChange 的方式执行此操作的效率略低,因为它声明了一个额外的匿名函数,但差异是如此之小,以至于主要的激励因素可能只是为了使代码可读并且看起来不错。

他们一定认为要执行 onChange 的代码块太大而不能放在那里,他们想将其包装在另一个函数中以保持代码的组织性。


推荐阅读