sass - 如何使用未定义数量的参数来匹配映射中的键并将它们添加为属性?
问题描述
基本上我想要实现的是一个 mixin,我可以通过在 mixin 中添加与映射中的特定键匹配的参数来指定元素将具有哪些属性。
例子
$map: (
width: 100px,
height: 100px,
background: red;
color: white;
);
此 mixin 的参数必须与 $map 中的键匹配。
@mixin specify-properties($props) {}
所以,如果我有这样的事情:
.element-1 {
@include specify-properties(width, background);
}
.element-2 {
@include specify-properties(width, height, color);
}
它将从 $map 输出 key:value
.element-1 {
width: 100px;
background: red;
}
.element-2 {
width: 100px;
height: 100px;
color: white;
}
解决方案
几个小时后我自己想通了,不确定这是否是最好的方法
$properties: (
width: 100px,
height: 100px,
color: red,
border: 2px
);
@mixin specify-properties($props...) {
@each $prop in $props {
$prop-value: map-get($properties, #{$prop});
#{$prop}: #{$prop-value};
}
}
使用混合:
.btn {
@include specify-properties(color, width, height);
}
我想要的输出:
.btn {
color: red;
width: 100px;
height: 100px;
//border won't appear since it's not specified in the argument.
}
如果 mixin 中的参数在 map 中不存在,则不会添加它,只会添加指定并存在的其余部分。
挺好看的,我觉得
推荐阅读
- asp.net-core - 为了响应在没有足够权限的情况下删除资源的请求,在休息 API 中引发的正确异常是什么?
- data-structures - 为什么我需要堆栈和队列?
- azure - 部署 Azure Web 作业
- react-native - “react-native init”模板应用程序的问题:无法从 react-native/scripts 解析模块`./index`
- html - 从jsp调用html文件
- c# - 如何从 ContentView 上下文中使用的 ListView 绑定“轻拍”事件处理程序?
- javascript - 如果有使用 fullCalendar 的事件,则突出显示日期
- amazon-web-services - 在 beanstalk t2.micro ec2 上找不到 Django 2.1.1
- c# - 在多租户应用场景中,同一模型是否可以具有不同的属性?
- sql - 按各种属性比较两个大表 - PostgreSQL