【问题标题】:Why does jsx require three dots in this code?为什么 jsx 在这段代码中需要三个点?
【发布时间】:2017-05-22 14:39:46
【问题描述】:

我找到了much upvoted answer 的问题,代码如下:

var condition = true;

return (
  <Button {...condition ? {bsStyle: 'success'} : {}} />
);

为什么需要...?如果我省略它,babel 会向我抱怨:

repl: Unexpected token, expected ...

它看起来像扩展语法,但condition 是一个布尔值。我很难找到解释发生了什么的文档。

【问题讨论】:

标签: reactjs babeljs react-jsx


【解决方案1】:

如果您查看MDN: Spread operator

展开语法允许表达式在以下位置展开 多个参数(用于函数调用)或多个元素(用于 数组文字)或多个变量(用于解构赋值) 预计。

如果你看到了,jsx语法里面的spread operator来求值表达式,那么

<Button {...condition ? {bsStyle: 'success'} : {}} />

会变成类似(after babel run with react bootstrap example):

_react2.default.createElement(_reactBootstrap.Button, condition ? { bsStyle: 'success' } : {})

也可以写成:

<Button bsStyle={condition ? 'success' : ''}  />

然后意味着你正在传递带有空字符串的道具bsStyle

因此,为了有条件地传递道具本身,您可以利用扩展运算符并评估表达式。这有助于我们通过条件传递多个道具:

<Button {...condition ? {bsStyle: 'success', bsSize:"large"} : {}} />

而不是:

<Button bsStyle={condition ? 'success' : ''} bsSize={condition ? 'large' : ''} />

【讨论】:

    【解决方案2】:

    您正在使用 boolean返回一个对象。扩展运算符... 的用法是用于扩展该对象,因此您可以使用括号使其更具可读性:

    var condition = true;
    <Button { ...(condition ? {bsStyle: 'success'} : {}) } />
    

    如果您的变量为真,则相当于此:

    <Button { ...{bsStyle: 'success'} } />
    

    如果您的变量为假,则为这个:

    <Button { ...{} } />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多