对于道具,这个对象初始化是如何工作的?

问题描述 投票:1回答:1

我找到了这段代码,并希望解释为什么在初始化后需要'= {}'。我能弄清楚的是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 />
....
javascript reactjs object initialization const
1个回答
1
投票
  1. 这是解构语法,而不是普通的变量赋值。从props提取的变量是consts并且不能重新分配的变量 - 即变量名为widthheightisActiveisOutsidexy。 (这里没有对象初始化 - 已经定义了props,作为函数的参数)
  2. = {}需要为elementDimensions提供默认值。没有它,如果width未定义,heightprops.elementDimensions的解构将失败:

const props = {};
const {
  elementDimensions: {
    width = 0,
    height = 0
  }
} = props;
  1. = props只是更多的解构语法。例如 const { foo } = bar;

foo对象中提取bar属性,并将其放入名为foo的变量中。

与上面的= bar类似,代码中的= propsprops对象中提取属性,并将它们放入变量名称中。

© www.soinside.com 2019 - 2024. All rights reserved.