css - 让节点 sass 生成一个类但也生成一个 mixin?
问题描述
我对 sass 相当陌生,我在想如果使用一些变量,我可以生成一些实用程序类和 mixin,我可以在 html 中使用,也可以在另一个 sass 文件中使用,而无需导入所有样式。
所以有两个问题:
我看到如果我导入“_color.scss”,所有类都会自动添加到导入的文件中。有什么方法可以输出我想要的吗?我知道你可以通过一些节点扩展来做到这一点,但这不是我想要的,想要一些可以与 sass 扩展一起使用的东西。
这就是我想要实现的目标:
_colors 文件:
$primary: black;
$secondary: blue;
//generate the classes and the mixins with the name of the variables like:
.bg-primary {
background-color: $primary;
}
@mixin bg-primary {
background-color: $primary;
}
因此,通过上述方式,我可以通过将类导入根来使用颜色,也可以只在组件中使用 mixin 而无需导入所有类。可能有更简单的方法可以做到这一点,因此欢迎任何替代方法。
更新:
这是实用程序mixin:
@mixin u($prop, $value: null) {
@if ($prop and $value) {
#{$prop}: call($prop, $value);
} @else {
.u-#{$prop} {
@each $item, $value in $color {
&-#{$item} {
#{$prop}: $value;
};
}
}
}
}
这是更改的颜色文件:
$color: (
primary-main: rgb(25, 118, 210),
secondary-main: rgb(220, 0, 78),
error-main: rgb(244, 67, 54),
warning-main: rgb(255, 152, 0),
info-main: rgb(33, 150, 243),
success-main: rgb(76, 175, 80),
text-primary: rgba(0, 0, 0, 0.87),
text-secondary: rgba(0, 0, 0, 0.54),
text-disabled: rgba(0, 0, 0, 0.38),
);
@function color($value:null) {
@if($value) {
@if map-has-key($color, $value) {
@return map-get($map: $color, $key: $value);
}
}
@return $color
};
现在的问题是,对于我想要的每个属性,我都需要创建一个同名的函数。有什么办法可以使这部分动态化吗?所以我不需要为字体、bg 等创建函数......
解决方案
知道了,
所以我将所有标记汇总在一张地图中。
然后我可以这样做:
@mixin u($prop, $value: null) {
@if ($prop and $value) {
#{$prop}: get-tokens($tokens, $prop, $value);
} @else {
.u-#{$prop} {
@each $item, $value in map-get($tokens, $prop) {
&-#{$item} {
#{$prop}: $value;
};
}
}
}
}
代币:
$tokens:(
border-color: $color,
color: $color,
background-color: $color,
font-size: $font-size,
font-weight: $font-weight,
font-family: $font-family,
);
@function get-tokens ($map, $keys...) {
@if type-of($map) != 'map' {
@error 'The argument $map: `#{$map}` is of incorrect type: `#{type-of($map)}`. Type of `Map` is required!';
}
@each $key in $keys {
$map: map-get($map, $key);
}
@return $map;
}
推荐阅读
- python - for 循环中的变量将成为外部循环 Python 的新迭代器
- postgresql - 如何从 PostgreSql 中具有数字、字符串和空值的列中仅选择数字值?
- c++ - 包括 curlpp 的问题
- svn - Tortoise SVN logminsize 和 externals
- c - 在 C 中使用 fmod() 总是导致零 (0)
- javascript - 在反应中使用 IntersectionObserver 更改滚动标题的样式
- c++ - 值作为可变参数模板的参数
- sql - pg_dump 插入按主键排序的 SQL 文件
- c - 使用 calloc 为 C 中的 char 数组分配内存时如何避免“可能丢失”的内存
- database - Flutter 从手动包含的数据库中填充列表