我正在忙于学习使用CSS模块的React,但我不太明白如何存储变量?例如,在Sass中,您可以这样做:
// _variables.scss
$primary-color: #f1f1f1;
// heading.scss
@import './variables';
.heading {
color: $primary-color
}
如何在CSS模块中实现这一点?
我正在忙于学习使用CSS模块的React,但我不太明白如何存储变量?例如,在Sass中,您可以这样做:
// _variables.scss
$primary-color: #f1f1f1;
// heading.scss
@import './variables';
.heading {
color: $primary-color
}
这是使用原始CSS模块的方法
// vars.css
:root {
--color-black: #222;
}
// myComponent.module.css
@import './vars.css';
.component {
color: var(--color-black);
}
CSS-Modules 文档在此处提到变量: https://github.com/css-modules/css-modules/blob/master/docs/values-variables.md
这样,您就可以像这样导入变量:
@value colors: "../../main/colors.css";
@value primary, secondary, tertiary from colors;
可以在你的CSS中使用:
.main {
background-color: tertiary;
border-top: 30px solid primary;
}
postcss-loader
和postcss-modules-values
添加到您的webpack配置中。请参见下文: {
test: /\.css$/,
use: [{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]_[local]_[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: [postcssModulesValues]
}
}
]
}
一种方法是使用依赖项。例如,
// variables.css
.primaryColor {
color: #f1f1f1
}
// heading.css
.heading {
composes: primaryColor from "./variables.css"
}
@Value
语法。 - Andrew如果您在 index.css
中添加根 CSS 变量,则可以全局访问这些变量,而无需使用 @import
这是基于默认文件结构的假设,即在 src/App.js
文件中导入了 index.css
。
CSS 模块是作用域限定的,这意味着其中的变量是局部的,但这并不意味着您不能从全局 CSS 文件中访问变量。
示例一
假设这是我们的 index.css
:root {
--header-width: 95vw;
--border-radius-one: 5px;
}
body {
background-color: #261d54;
margin: 0;
font-family: "Poppins", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#header {
margin: 0 auto;
width: var(--header-width);
border:1px solid blue;
border-radius: var(--border-radius-one);
}
onClick
。
示例二
function changeFontSize(size){
document.documentElement.setProperty('--font-size', size)
}
return(
<div>
<button onClick={() => changeFontSize('18px')}>
set font size to 18px
</button>
<button onClick={() => changeFontSize('12px')}>
set font size to 12px
</button>
</div>
)
如果你想了解关于documentElement的内容,请点击这里。
您可以使用sass预处理器和sass-resources-loader。
sass-resources-loader会将所有变量、mixin等添加到每个需要的sass文件中。
localIdentName
has now moved inside modules. You may wanna do:modules: {auto: true, localIdentName: "[name]_[local]_[hash:base64:5]",}
- KJ Sudarshan