CSS 模块 https://github.com/css-modules/css-modules与 SASS 或 SCSS 无关,并且有自己的一组支持的功能和关键字。是的,它们可以一起使用,我在大多数项目中实际上都是这样做的。但我避免不同文件之间存在类名依赖关系。我知道一些可用于共享类名的功能,但避免使用它可能是最好的解决方案。我将在下面的部分列出我能想到的解决您的难题的所有潜在解决方案;选择最适合您的:
- 解决方案#1:永远不要共享类名,将属于一起并在相同类名上运行的样式放在一起。
在您的情况下,这意味着您只有一个与按钮相关的 scss 文件
buttons.modules.scss
以及两者Button.js
and ButtonGroup.js
导入它。
- 解决方案#2:从唯一生成的名称机制将它们标记为
:global
。这可以这样完成:
// button.module.scss
// this will stay a global classname
:global(.button) {
// the button styles
}
// this will be treated as usual, generating a local name
.icon {
// some icon stuff
}
// buttongroup.module.scss
.buttonGroup {
display: flex;
// will be resolved as local classname
&.horizontal {
flex-direction: row;
// will be resolved as global classname
& > :global(.button):not(:first-child) { margin-left: 1rem; }
}
&.vertical {
flex-direction: column;
& > :global(.button):not(:first-child) { margin-top: 1rem; }
}
}
- 解决方案#3:接受匿名儿童。您可以省略子级的类名。没有人将非按钮放置在按钮组中(甚至可能在组件代码中强制执行它)。
// buttongroup.module.scss
.buttonGroup {
display: flex;
&.horizontal {
flex-direction: row;
& > *:not(:first-child) { margin-left: 1rem; }
}
&.vertical {
flex-direction: column;
& > *:not(:first-child) { margin-top: 1rem; }
}
}
- 解决方案#4:引用另一个文件的内容。似乎有一些支持可以从其他文件引用/导入内容的语法,但我仔细阅读了文档和一些 github 问题讨论'从文件名导入类名' https://github.com/css-modules/css-modules/issues/40 'more' https://github.com/css-modules/css-modules/issues/25 '和更多' https://github.com/css-modules/css-modules-loader-core/pull/28没有得到任何关于如何从另一个文件导入本地类名的明确答案。沿着这些思路可能有一些可能see here https://github.com/css-modules/css-modules-loader-core/pull/28:
@import button from './button.module.scss';
.buttonGroup {
display: flex;
&.horizontal {
flex-direction: row;
& > .button:not(:first-child) { margin-left: 1rem; }
}
&.vertical {
flex-direction: column;
& > .button:not(:first-child) { margin-top: 1rem; }
}
}
...或者沿着这些思路see here https://github.com/css-modules/css-modules/issues/40#issuecomment-135655919:
:import("./button.module.scss") {
imported-button: button;
}
.buttonGroup {
display: flex;
&.horizontal {
flex-direction: row;
& > .imported-button:not(:first-child) { margin-left: 1rem; }
}
&.vertical {
flex-direction: column;
& > .imported-button:not(:first-child) { margin-top: 1rem; }
}
}
- 解决方案#5:让您的容器组件添加一个类
.button-group-item
到每个孩子并用它来应用边距而不是.button
class.