reactjs - 传播语法 ecmascript
问题描述
我以前使用过传播语法,但不是以这种方式。(...fns)
我对to之间的跳转感到困惑(...args)
。我知道这fns
是传入的函数(internalOnLoad 和 onLoad),并且是args
属于相应函数的参数。但是当每个函数都将它们的参数传递给函数 (...args) => fns.forEach(...) 时会是什么样子?
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
const internalOnLoad = () => console.log("loaded");
const Avatar = ({ className, style, onLoad, ...props }) => (
<img
className={`avatar ${className}`}
style={{ borderRadius: "50%", ...style }}
onLoad={callAll(internalOnLoad, onLoad)}
{...props}
/>
);
Avatar.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string,
style: PropTypes.object,
onLoad: PropTypes.func
};
你能给我一个视觉描述这会是什么样子吗?例如,这样的调用callAll = (...fns)
:callAll(internalOnLoad, onLoad)
与 callAll 相同,将接收这样的参数callAll = (internalOnLoad, onLoad)
先感谢您
解决方案
其余参数语法将所有参数收集到一个数组中。在这种情况下,部分应用程序用于存储函数数组 ( fns
),并返回一个新函数。调用新函数时,它将调用 中的函数fns
,并将参数 ( args
) 传递给每个函数。
如果我们使用标准的 JS 函数,它将是:
function callAll(...fns) {
return (...args) {
fns.forEach(fn => fn && fn(...args));
}
}
例子:
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
const callFns = callAll (
(a, b) => console.log(a + b + 10),
(a, b) => console.log(a + b + 20),
(a, b) => console.log(a + b + 30),
);
console.log(callFns); // you can see the function that was returned in the console.
callFns(1, 2);
推荐阅读
- express - 问题:如何将Express Server的console.log发送到前端
- python - 执行 Python 请求以使用 API 上传 base64 字符串(上传 NFT)
- sql-server - 如何修复,操作系统返回错误 '0xc0000033(Object Name invalid.)',试图在 FILESTREAM 数据库中插入图像数据
- vue.js - Vue js axios 获取请求错误-对预检请求的响应未通过访问控制检查:不存在“Access-Control-Allow-Origin”标头
- html - 带有弹性容器和显示背景图像的引导布局登录页面问题
- amazon-web-services - 如何使用 AWS Crawler 为动态 S3 路径创建 Athena 表?
- python-3.x - 使用 networkx 在图中添加节点时出错
- python - 2 .feather 文件具有相同的数据,完全不同的大小?
- node.js - 如何从rest api中的json文件中检索数据
- laravel - Laravel 自定义电子邮件验证模板不起作用