我以前使用过扩展语法,但不是以这种方式。我对从(...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 = (internalOnLoad, onLoad)参数
提前谢谢你
发布于 2018-07-18 21:49:18
在本例中,partial application用于存储函数数组(fns),并返回一个新函数。当新函数被调用时,它将调用fns中的函数,并将参数(args)传递给每个函数。
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);
发布于 2018-07-18 21:55:20
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
第一个...获取所有函数。
第二个...获取所有参数。
第三个...将带有fn.apply(undefined, args)的参数插入到函数中,而不是插入fn(args)。
https://stackoverflow.com/questions/51403615
复制相似问题