嵌套对象解构:重复声明“fontSize”

时间:2017-11-13 10:36:32

标签: javascript ecmascript-6 styled-components

我正在使用带有样式组件的ShevyJS。文档显示了使用nested object deconstruction ...

的示例
const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  }
} = shevy

和我的风格......

const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

工作正常。但是,如果我尝试执行以下操作,则会收到错误Module build failed: Duplicate declaration "fontSize" ...

const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  },
  p: {
    fontSize
  }
} = shevy

const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${fontSize};
`;

我之前从未使用过嵌套对象。我假设fontSize中的p范围为ph1范围为h1,以便styled.p知道fontSize使用。它肯定会有意义,但我非常怀疑它是如何工作的。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的解构声明基本上等同于

const fontSize = shevy.h1.fontSize,
      fontSize = shevy.p.fontSize;

显然无效。如果要对它们进行解构,则需要将它们分配给不同的变量。

  

我认为fontSize中的p范围限定为ph1范围限定为h1,以便styled.p知道fontSize {1}}要使用。

不,没有这样的范围,它与嵌套对象没有任何关系。解构目标中的所有变量都在同一范围内声明 - 它们只是普通的const变量,没有附加名称空间的任何变量。

请记住,styled.p只是一个模板标记,它对变量名称一无所知,或者能够以任何方式影响它们。在将结果传递到标记函数之前,模板的插值部分中的表达式将照常计算。

如果你想做一些命名空间,你需要自己明确地做:

const {
  baseSpacing: bs,
  h1: {
    fontSize: h1Fontsize,
//          ^^^^^^^^^^^^
    lineHeight,
    marginBottom
  },
  p: {
    fontSize: pFontsize
//          ^^^^^^^^^^^
  }
} = new Shevy();

const Heading = styled.h1`
    font-size: ${h1FontSize};
/*               ^^ */
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${pFontSize};
/*               ^ */
`;
相关问题