我的“src”文件夹大致如下:
components/
[all components]
theme/
themes/
lightTheme.less
darkTheme.less
palette.less
palette.less:
@import './themes/lightTheme.less';
然后,在每个想要使用主题颜色的组件中,我都会这样做:
component.module.less:
@import '../../theme/palette.less';
.element {
background-color: @primary;
}
这种结构使我能够编辑palette.less
并导入我想要使用的主题。但问题是我希望用户能够自行选择他们喜欢的主题。主题应该在运行时可切换,这意味着我需要同时拥有这两个主题。
我设想的完美解决方案如下:
app.less
body {
@theme: @light-theme;
&.dark-theme {
@theme: @dark-theme;
}
}
然后在每个组件中导入 @theme
变量,并从中读取属性(即 @theme[primary]
)。
不幸的是,Less 变量的作用域并不像这样工作。
我对任何使用 Less 模块的解决方案持开放态度。
谢谢!
css in js
,例如 styled-components、emotion等,然后使用ThemeProvider
,可以轻松地通过编程方式切换多个主题。 - gadi tzkhori.styled.js
文件,除了它们绝对不是组件之外,其他都是组件...) - Itay Ganor