我找到了这段代码,并希望解释为什么在初始化后需要'= {}'。我能弄清楚的是1)const使'props'对象const(不是它的内容)2)'elementDimensions.width'等字段被初始化但对象设置为= {},为什么需要它? 3)最后它是'= props','props'可能会为这个对象添加字段?谢谢。
export default (props) => {
const {
elementDimensions: {
width = 0,
height = 0
} = {},
isActive = false,
isOutside = true,
point: {
x = 0,
y = 0
} = {}
} = props;
return (
<div>
{`x: ${x}`}<br />
....
props
提取的变量是const
s并且不能重新分配的变量 - 即变量名为width
,height
,isActive
,isOutside
,x
和y
。 (这里没有对象初始化 - 已经定义了props
,作为函数的参数)= {}
需要为elementDimensions
提供默认值。没有它,如果width
未定义,height
和props.elementDimensions
的解构将失败:const props = {};
const {
elementDimensions: {
width = 0,
height = 0
}
} = props;
= props
只是更多的解构语法。例如
const { foo } = bar;
从foo
对象中提取bar
属性,并将其放入名为foo
的变量中。
与上面的= bar
类似,代码中的= props
从props
对象中提取属性,并将它们放入变量名称中。