Sass 检查变量是否传递给 mixin [英] Sass check if variable is passed to mixin
问题描述
假设我有一个带有默认值的 mixin
Lets say I have a mixin with default values
$default: 1;
@mixin test($p : $default) {
@if () {
// Do something if $p was 4passed?
} @else {
// Do something if $p was not passed?
}
}
如果我像这样调用 mixin,两个不同的是:
If I was to call the mixin like so, two different was:
@include test(); // A
@include test(1); // B
有什么方法可以区分默认 (A) 和覆盖默认 (B) 的区别?
Is there a way I can tell the difference between the default (A), and the one that's overwriting the default (B)?
推荐答案
如果你稍微修改一下你的 mixin 就会工作(因为你实际上需要将有问题的参数传递给 @if
指令.并且您可能希望将参数默认为 null
或 false
,这意味着没有传递任何内容).
Your mixin would work if you modify it a tiny bit (as you actually need to pass the parameter in question to the @if
directive. And you would want to default the parameter to null
or false
, which would mean that nothing was passed).
@mixin test($p: null) {
@if ($p) {
/* Do something if $p was passed */
} @else {
/* Do something if $p was not passed */
}
}
如果你想设置一个不同的值作为默认值,那么你只需要在 if 语句中检查那个特定的值(例如如果 $p
被设置为默认值,那么做一些事情").在这里,您将如何通过设置变量的默认值来执行此操作,就像在示例中一样.但是,这不会区分无参数传递"和传递的值等于默认值".
If you want to set a different value as the default, then you just need to check for that specific value in the if statement (e.g. "do something if $p
is set to the default value"). Here how you would do this by setting the default from a variable, like you do in your example. However, this will not differentiate between "no argument passed" and "passed value equals default value".
@mixin test($p: $default) {
@if ($p == $default) {
/* Do something if $p is set to $default */
} @else {
/* Do something else if $p is not $default */
}
}
但是对于 corse,你可以结合这两种方法......检查是否有东西传递给 $p
(如果传递或不传递则做不同的事情),如果没有传递 set $p
的默认值.
But of corse you can combine both approaches ... check if something is passed to $p
(to do different things if passed or not), and if nothing is passed set $p
's value to default.
@mixin test($p: null) {
@if ($p) {
/* Do something if argument passed */
} @else {
/* Do something else if no argument passed. Set $p to default. */
$p: $default;
}
}
这现在应该适用于除 false
的布尔值之外的所有内容,因为 null
和 false
都验证为 false
与 @if
指令.因此,要允许将 false
作为参数值传递,您需要使用更具体的表达式.例如:
This should now work for everything but the boolean value of false
, as null
and false
both validate to false
with the @if
directive. So to allow passing false
as an argument value you would need to use a more specific expression. For example:
...
@if ($p != null) {
...
瞧,这应该可以解决问题 - 除非您出于某种原因想要将 null
作为参数传递.然后你需要使用其他东西作为默认值,比如一个极不可能作为参数传递的字符串,例如没有传递参数"
=)
And voilà, this should do the trick - unless you, for some reason, want to pass null
as an argument. Then you need to use something else as the default, like a string that is extremely unlikely to be passed as an argument, e.g. "no arguments have been passed"
=)
这篇关于Sass 检查变量是否传递给 mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!