reactjs - 返回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 创建了一个回调。
我想知道何时以及为什么应该使用每种解决方案。预先感谢您的澄清。
解决方案
你是对的,它与声明的匿名函数的数量有关。
以他们使用 handleChange 的方式执行此操作的效率略低,因为它声明了一个额外的匿名函数,但差异是如此之小,以至于主要的激励因素可能只是为了使代码可读并且看起来不错。
他们一定认为要执行 onChange 的代码块太大而不能放在那里,他们想将其包装在另一个函数中以保持代码的组织性。
推荐阅读
- unity3d - Photon - OnLeftRoom 意外调用
- python-3.x - 正则表达式匹配 2 到 5 个字符,其中一个必须是字母
- r - @Param Plumber 不适用于 Highcharts - R
- amazon-web-services - AWS - 如何将 ARN 从云形成模板传递到 aws lambda 函数
- google-cloud-platform - 将 Google Cloud Build 连接到 Google Cloud SQL
- asp.net-mvc - 聚合数据时使 Kendo Grid 中的列可调整大小
- android - 将来自 github 操作的工件添加到发布
- flutter - 如何使用 Dart 获取时间范围内每周的列表?
- android - 生命周期观察者奇怪的行为
- python - Raspberry Pi、Python 和 Docker 的热敏打印机配置错误