在SASS中如何通过引用传递函数或Mixin

3
有没有办法在SASS中将函数或mixin作为引用传递给另一个函数或mixin,并调用所引用的函数或mixin?
例如:
@function foo($value) {
    @return $value;
}

@mixin bob($fn: null) {
    a {
        b: $fn(c); // is there a way to call a referenced function here?
    }
}

@include bob(foo); // is there any way I can pass the function "foo" here?

现在您可以通过meta.get-function()返回的函数进行传递。但是您仍需使用meta.call()来调用它。 - Kal
1个回答

6

在Sass中,函数和mixin不是一等公民,这意味着您无法像处理变量那样将它们作为参数传递。

Sass 3.2及更早版本

最接近的方法是使用@content指令(Sass 3.2+)。

@mixin foo {
    a {
        @content;
    }
}

@include bob {
    b: foo(c); // this replaces `@content` in the foo mixin
}

唯一的注意事项是@content看不到mixin内部的内容。换句话说,如果c只在bob mixin内定义,它基本上不存在,因为它不在范围内。
Sass 3.3及更高版本
从3.3开始,您可以使用call()函数,但它仅用于函数而非mixin。这需要将包含函数名称的字符串作为第一个参数传递。
@function foo($value) {
    @return $value;
}

@mixin bob($fn: null) {
    a {
        b: call($fn, c);
    }
}

@include bob('foo');

将字符串传递给call()已被弃用,并且在Dart Sass 2.0.0中将是非法的。现在,您应该传递由meta.get-function()返回的函数。 - Kal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接