在 SASS 中通过引用传递函数或 mixin

Phi*_*ant 3 css sass

有没有办法通过引用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?
Run Code Online (Sandbox Code Playgroud)

cim*_*non 6

函数和 mixins 在 Sass 中并不是一流的,这意味着你不能像使用变量那样将它们作为参数传递。

Sass 3.2 及更早版本

您可以获得的最接近的是指令@content(Sass 3.2+)。

@mixin foo {
    a {
        @content;
    }
}

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

唯一需要注意的是,他们@content看不到你的 mixin 里面有什么。换句话说,如果c仅在bobmixin 内定义,它基本上不会存在,因为它不在范围内考虑。

Sass 3.3 及更高版本

从3.3开始,你可以使用该call()函数,但它只能与函数一起使用,不能与mixins一起使用。这需要传递包含函数名称的字符串作为第一个参数。

@function foo($value) {
    @return $value;
}

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

@include bob('foo');
Run Code Online (Sandbox Code Playgroud)