【问题标题】:Spread Operator ... used with function call in props of Tab in material UISpread Operator ... 与 Material UI 中 Tab 的 props 中的函数调用一起使用
【发布时间】:2021-09-26 02:12:20
【问题描述】:

我在 Material UI 中看到了这个<Tab label="Item One" {...a11yProps(1)} />,其中函数在道具中使用...展开运算符调用当我尝试时

console.log(...a11yProps(3));

我得到错误,任何人都可以告诉这里发生了什么<Tab label="Item One" {...a11yProps(1)} /> 扩展运算符如何与函数调用一起使用?

【问题讨论】:

  • See my answer here。开头广泛讨论了为什么“传播”不是操作员以及为什么这很重要。简而言之,...fn() 会根据上下文做不同的事情。对象传播{...fn()}必须接收一个对象,而传播到参数console.log(...fn())必须接收一个迭代。大多数情况下,它们不会重叠。
  • @VLAZ 我已经阅读了你的答案,但我没有得到函数调用使用的传播语法的答案?一段时间后我问这个问题,因为我又面临这个问题了!
  • 让我重申一下 - 传播不是一回事。取决于上下文。在函数调用中,您只能传播 arrays(或其他可迭代对象)。传播 一个对象 是完全不同的事情,并且在函数调用中不起作用。对象可以传播到其他对象中。所以...x 会根据x 是什么以及上下文是什么而发生变化fn( ...x ){ ...x } 是不同的操作,因为上下文不同。
  • @VLAZ 嗯,先生,还有更好的演示!请,抱歉打扰了。

标签: javascript reactjs material-ui react-props


【解决方案1】:

演示


function fn(x, y, z) {
  console.log("fn() called with", x, y, z);
}
let x;

x = ["a", "b", "c"];


fn( ...x ); //function call with spread of an array

console.log("spreading into an object", { ...x } ); // spreading into an object clones the properties of the array

x = {a: 1, b: 2, c: 3};

console.log("spreading into an object", { ...x } ); // spreading object into an object clones it

fn( ...x ); //spreading an object into a function call is an error



function fb2(){
  return obj = {object : 'new Object'}
}

console.log({...fb2()}.object);

【讨论】:

    【解决方案2】:

    只要做:

    console.log(a11yProps(3));
    

    【讨论】:

    • 我知道我要问的是扩展运算符与函数一起使用并作为道具传递<Tab label="Item One" {...a11yProps(1)} />
    • @MuhammadMehdi 是的,它在那里作为道具传递,如果你想 console.log 它你必须在没有传播运算符的情况下记录它,你想在这里实现什么?你甚至测试过我的答案吗?
    • 我想知道它是如何用起始展开运算符调用函数的!
    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2020-03-31
    相关资源
    最近更新 更多