reactjs - 扩展语法 ecmascript

标签 reactjs ecmascript-6

我以前使用过扩展语法,但不是这样的。我对 (...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/

相关文章:

reactjs - 在 React 中,是否可以从实用函数内部访问 Redux 操作创建者?

node.js - 如何使用 ES6 在 NodeJS 中创建具有异步导出的模块

javascript - 未捕获的类型错误 INCLUDES 不是函数

javascript - 状态内 react 组件的动态加载

javascript - 将 api 响应推送到 .map() 中的全局变量以某种方式使数据无法访问

javascript - ES6/React 第二项绑定(bind)失败

javascript - 了解 .reduce() 中的许多函数参数

javascript - 同值零算法如何工作?

javascript - 在计时器上循环显示/隐藏 React 组件

javascript - 如何将带有状态变量的jsx导入到另一个react组件中?