为什么jsx在此代码中需要三个点?
Why does jsx require three dots in this code?
我找到了一个 问题,代码如下:
var condition = true;
return (
<Button {...condition ? {bsStyle: 'success'} : {}} />
);
为什么需要...?如果我省略它,babel 会向我抱怨:
repl: Unexpected token, expected ...
它看起来像传播语法,但 condition
是一个布尔值。我找不到解释发生了什么的文档。
如果你签出 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 语法中的扩展运算符对表达式求值,那么
<Button {...condition ? {bsStyle: 'success'} : {}} />
会变成类似 (after babel run with react bootstrap example)
:
_react2.default.createElement(_reactBootstrap.Button, condition ? { bsStyle: 'success' } : {})
也可以写成:
<Button bsStyle={condition ? 'success' : ''} />
然后 意味着你正在传递带有空字符串 的道具 bsStyle
。
因此,为了有条件地传递 props 本身,您可以利用展开运算符并对表达式求值。这有助于我们在条件下传递多个道具:
<Button {...condition ? {bsStyle: 'success', bsSize:"large"} : {}} />
而不是:
<Button bsStyle={condition ? 'success' : ''} bsSize={condition ? 'large' : ''} />
您正在使用 布尔值 到 return 对象。扩展运算符 ...
用于扩展该对象,因此您可以使用括号使其更具可读性:
var condition = true;
<Button { ...(condition ? {bsStyle: 'success'} : {}) } />
这等同于此,如果您的变量为真:
<Button { ...{bsStyle: 'success'} } />
如果您的变量为假,则为这个:
<Button { ...{} } />
我找到了一个
var condition = true;
return (
<Button {...condition ? {bsStyle: 'success'} : {}} />
);
为什么需要...?如果我省略它,babel 会向我抱怨:
repl: Unexpected token, expected ...
它看起来像传播语法,但 condition
是一个布尔值。我找不到解释发生了什么的文档。
如果你签出 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 语法中的扩展运算符对表达式求值,那么
<Button {...condition ? {bsStyle: 'success'} : {}} />
会变成类似 (after babel run with react bootstrap example)
:
_react2.default.createElement(_reactBootstrap.Button, condition ? { bsStyle: 'success' } : {})
也可以写成:
<Button bsStyle={condition ? 'success' : ''} />
然后 意味着你正在传递带有空字符串 的道具 bsStyle
。
因此,为了有条件地传递 props 本身,您可以利用展开运算符并对表达式求值。这有助于我们在条件下传递多个道具:
<Button {...condition ? {bsStyle: 'success', bsSize:"large"} : {}} />
而不是:
<Button bsStyle={condition ? 'success' : ''} bsSize={condition ? 'large' : ''} />
您正在使用 布尔值 到 return 对象。扩展运算符 ...
用于扩展该对象,因此您可以使用括号使其更具可读性:
var condition = true;
<Button { ...(condition ? {bsStyle: 'success'} : {}) } />
这等同于此,如果您的变量为真:
<Button { ...{bsStyle: 'success'} } />
如果您的变量为假,则为这个:
<Button { ...{} } />