加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 为什么jsx在这段代码中需要三个点?

发布时间:2020-12-15 20:31:43 所属栏目:百科 来源:网络整理
导读:我用以下代码找到了一个问题的 much upvoted answer: var condition = true;return ( Button {...condition ? {bsStyle: 'success'} : {}} /); 为什么……需要?如果我省略它,babel抱怨我: repl: Unexpected token,expected ... 它看起来像扩展语法,但条件
我用以下代码找到了一个问题的 much upvoted answer:

var condition = true;

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

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

repl: Unexpected token,expected ...

它看起来像扩展语法,但条件是布尔值.我找不到解释发生了什么的文档.

解决方法

如果你看看 MDN: Spread operator:

The spread syntax allows an expression to be expanded in places where
multiple arguments (for function calls) or multiple elements (for
array literals) or multiple variables (for destructuring assignment)
are expected.

如果你看到,jsx语法中的spread运算符来计算表达式,那么

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

会变成类似的东西(在babel运行反应引导程序后):

_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' : ''} />

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读