【问题标题】:Spreading operator doesn't work the same as assigning an object in React JS [duplicate]扩展运算符与在 React JS 中分配对象的工作方式不同 [重复]
【发布时间】:2020-08-10 21:00:57
【问题描述】:

当我执行以下操作时,一切正常:

this.state.sections.map(({ a, b }) => <MenuItem { ...{a,b} }/>)

但是,当我执行以下操作(我认为这是等效的)时,我收到一条错误消息,提示 ... 应该是:

this.state.sections.map(({ a, b }) => <MenuItem { a, b }/>)

为什么会这样? ...{a,b}在JS中不就相当于a, b吗?

【问题讨论】:

  • "...{a,b} 不等于 JS 中的a, b 吗?" 不,不是。一个创建一个新对象,另一个使用comma operator,它会忽略a,只给你b。然而,对于 JavaScript 来说,这里的 React 语法可能是另一回事——我并不精通它。
  • @VLAZ 所以...{a,b} 的等价物是{a,b},对吧?
  • { a, b } 中的括号用来表示一个javascript表达式作为JSX中的prop(将a, b作为prop执行,因为prop没有名字所以无效) , 而 ...{a,b} 是在道具上模拟扩展运算符,其中键名用作道具名称。

标签: javascript reactjs babeljs jsx


【解决方案1】:

它们在 JSX 上下文中不等价:

// For given function component
const MenuItem = ({ a, b }) => <></>

// Use cases
(props /* {a,b} */) => <MenuItem {...props} />
<MenuItem a={a} b={b} />
<MenuItem { ...{a,b} }/>

// Transpiles to
React.createElement(MenuItem, { a, b });
// Syntax Error
// as this JSX doesn't transpile to React.createElement 
<MenuItem {a, b} />

/*
Unexpected token, expected "..." (1:11)
> 1 | <MenuItem {a, b} />;
*/

但在 JS 中,它们确实会产生相同的结构:

a = 5;
b= 7;
{ a, b } // { a: 5, b: 7 }
{ ...{ a, b } // { a: 5, b: 7 }

注意 babel 编译器和 JS 转译的代码的区别。

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2022-01-12
    • 2019-05-26
    • 2014-09-04
    • 2020-04-13
    • 2017-02-23
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多