【问题标题】:Nested object destructuring: Duplicate declaration "fontSize"嵌套对象解构:重复声明“fontSize”
【发布时间】:2018-04-26 00:23:09
【问题描述】:

我将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};
`;

我以前从未以这种方式处理过嵌套对象。我假设p 中的fontSize 的范围为ph1 的范围为h1,以便styled.p 知道要使用哪个fontSize。这当然是有道理的,但我非常怀疑它是如何工作的。

有什么想法吗?

【问题讨论】:

  • 给它一个唯一的名字?喜欢pFontSize
  • 您想将哪些fontSizes 用于Byline?但也不要做 CSS-in-JS 的事情
  • 在解构时,您将 shevy 属性分配给新的变量名。这些必须是独一无二的。为什么不直接使用 shevy 属性,shevy.fontSize
  • @Ryan 使用样式组件绝对没有错。它有助于为一个人维护 React 组件。请给我一个不好的理由。

标签: javascript ecmascript-6 styled-components


【解决方案1】:

你的解构语句基本上等同于

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

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

我假设p 中的fontSize 的范围为ph1 的范围为h1,以便styled.p 知道要使用哪个fontSize

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

请记住,styled.p 只是一个模板标签,它对变量名一无所知,或者可能以任何方式影响它们。模板的插值部分中的表达式在它们的结果 values 被传递到标记函数之前像往常一样进行评估。

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

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};
/*               ^ */
`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2018-05-02
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多