我以前使用过扩展语法,但不是这样的。我对 (...fns)
到 (...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 = (内部OnLoad,onLoad)
提前谢谢
最佳答案
rest parameters syntax将所有参数收集到一个数组中。在这种情况下partial application用于存储函数数组(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);
关于reactjs - 扩展语法 ecmascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51403615/