无法理解 JSX 点差运算符 [英] Trouble understanding JSX spread operator
问题描述
给出来自 React 文档的示例代码:
Given this example code from the React docs:
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
我对 ...props
实际评估的结果做了一些调查,这是:
I did some looking into what ...props
actually evaluates to, which is this:
React.__spread({}, props)
依次计算为 {foo: x, bar: y}
.
但我想知道的是,为什么我不能这样做:
But what I'm wondering is, why can't I just do this:
var component = <Component props />;
我不明白展开运算符的意义是什么.
I don't see understand what the point of the spread operator is.
推荐答案
这有助于使您的代码更加简洁 - 由于 props
是一个对象,因此扩展运算符采用 属性 您传入的对象并将它们应用于组件.因此,组件将具有值为 x
的 foo
和值为 y
的 bar
属性.
This helps make your code more succinct - since props
is an object, the spread operator takes the properties of the object you pass in and applied them to the component. So the Component will have properties a foo
with a value of x
and a bar
with a value of y
.
这将是相同的:
var component = <Component foo={props.foo} bar={props.bar} />;
更短
这篇关于无法理解 JSX 点差运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!