首页 > 解决方案 > 传播语法 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)

先感谢您

标签: reactjsecmascript-6

解决方案


其余参数语法将所有参数收集到一个数组中。在这种情况下,部分应用程序用于存储函数数组 ( 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);


推荐阅读