首页 > 解决方案 > 如何使用未定义数量的参数来匹配映射中的键并将它们添加为属性?

问题描述

基本上我想要实现的是一个 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;
}

标签: sass

解决方案


几个小时后我自己想通了,不确定这是否是最好的方法

$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 中不存在,则不会添加它,只会添加指定并存在的其余部分。

挺好看的,我觉得


推荐阅读