Javascript 嵌套对象解构:重复声明“;fontSize“;
我正在使用样式化组件。文档显示了一个使用 还有我的风格Javascript 嵌套对象解构:重复声明“;fontSize“;,javascript,ecmascript-6,styled-components,Javascript,Ecmascript 6,Styled Components,我正在使用样式化组件。文档显示了一个使用 还有我的风格 const Heading = styled.h1` font-size: ${fontSize}; line-height: ${lineHeight}; margin-bottom: ${marginBottom}; `; 它很好用。但是,如果我尝试执行以下操作,我会得到一个错误模块构建失败:重复声明“fontSize” const shevy = new Shevy() const { baseSpaci
const Heading = styled.h1`
font-size: ${fontSize};
line-height: ${lineHeight};
margin-bottom: ${marginBottom};
`;
它很好用。但是,如果我尝试执行以下操作,我会得到一个错误模块构建失败:重复声明“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
的范围是p
,而h1
的范围是h1
,因此styled.p
知道使用哪个fontSize
。这当然是有道理的,但我高度怀疑它是如何工作的
有什么想法吗?你的解构语句基本上等同于
const fontSize = shevy.h1.fontSize,
fontSize = shevy.p.fontSize;
这显然是无效的。如果要对它们进行分解,需要将它们分配给不同的变量
我假设p
中的fontSize
的范围是p
,而h1
的范围是h1
,因此styled.p
知道使用哪个fontSize
不,没有这样的作用域,它与嵌套对象没有任何关系。解构目标中的所有变量都在同一范围内声明-它们只是普通的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};
/* ^ */
`;
给它一个唯一的名字?像
pFontSize
?您希望将那些fontSize
s中的哪一个用于Byline
?但也不要在JS中使用CSS,当你将shevy属性分配给新的变量名时。这些需要是独特的。为什么不直接使用shevy属性,shevy.fontSize
?@Ryan使用样式化组件绝对没有错。它有助于维护一个组件的React组件。请给我一个合理的理由,为什么它不好。
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};
/* ^ */
`;