我正在尝试动态创建实用程序类。
可以在SASS中定义地图,然后在@each
处使用,以基于地图的key
和value
生成类。但是,需要在property
中手动添加css @each
。我想要一个可以添加该元素和一些基于地图数据的命名约定的函数。因此,基于以下示例,我想动态添加flex-direction
,而不必为每个地图创建一个@each
。
有效的方法:
//Example Map
@flex-wrap: ("nw": "no-wrap", "w": "wrap", "wr": "wrap-reverse")
//Example @each
@each $name, $value in $flex-wrap
.flx-w-#{$name}
flex-direction: #{$value}
我需要的:
.flx + $prefix + $name
$property: $value
以及预期的已编译CSS结果:
.flx-d-w {
flex-direction: wrap;
}
答案 0 :(得分:0)
一种执行所需操作的动态方法是使用嵌套映射,两个@each
循环和一个mixin。
$flex-direction: (
"name": "flex-direction",
"prefix": "flx-d",
"values": (
"r": "row",
"c": "column",
"rr": "row-reverse",
"cr": "column-reverse"
)
);
$flex-wrap: (
"name": "flex-wrap",
"prefix": "flx-w",
"values": (
"nw": "nowrap",
"w": "wrap",
"wr": "wrap-reverse"
)
);
@mixin createClasses($maps...) {
@each $map in $maps {
$propertyName: map-get($map, "name");
$propertyPrefix: map-get($map, "prefix");
@each $value, $key in map-get($map, "values") {
.#{$propertyPrefix}-#{$value} {
#{$propertyName}: #{$key};
}
}
}
}
@include createClasses($flex-direction, $flex-wrap);
使用上面的示例,您将获得:
.flx-d-r {
flex-direction: row;
}
.flx-d-c {
flex-direction: column;
}
.flx-d-rr {
flex-direction: row-reverse;
}
.flx-d-rc {
flex-direction: column-reverse;
}
.flx-w-nw {
flex-wrap: nowrap;
}
.flx-w-w {
flex-wrap: wrap;
}
.flx-w-wr {
flex-wrap: wrap-reverse;
}
这里的“魔术”部分是使用扩展...
运算符在mixin(documentation here)中传递任意数量的地图。您只需在所有地图上调用一次,它将创建您所有的类。
SASS版本的代码:
$flex-direction: ("name": "flex-direction", "prefix": "flx-d", "values": ("r": "row", "c": "column", "rr": "row-reverse", "cr": "column-reverse"))
$flex-wrap: ("name": "flex-wrap", "prefix": "flx-w", "values": ("nw": "nowrap", "w": "wrap", "wr": "wrap-reverse"))
=createClasses($maps...)
@each $map in $maps
$propertyName: map-get($map, "name")
$propertyPrefix: map-get($map, "prefix")
@each $value, $key in map-get($map, "values")
.#{$propertyPrefix}-#{$value}
#{$propertyName}: #{$key}
+createClasses($flex-direction, $flex-wrap)