使用可选参数制作 SCSS 混合失败的原因是什么?
What is the cause of this failure to make a SCSS mixin with an optional parameter?
我需要一个 SCSS mixin 来制作边框。在这个 mixin 中,$position
变量应该是可选的:
@mixin border($position, $width, $style, $color) {
@if $position {
border-#{$position}: $width $style $color;
} @else {
border: $width $style $color;
}
}
这是必要的,以便我可以在这两种情况下使用它:
.box {
@include border('bottom', 1px, solid, #999) /*with position*/;
}
和
.button {
@include border(1px, solid, #999); /*without position*/
@include border-radius(9999999px);
padding: .5rem .75rem;
font-size: 14px;
}
对于第二种情况,编译器抛出错误:
Mixin border is missing argument $color.
我做错了什么?
您可以为$position 使用默认参数。我使用 false
布尔值作为默认变量。
@mixin border($width, $style, $color, $position: false) {
@if $position {
border-#{$position}: $width $style $color;
} @else {
border: $width $style $color;
}
}
你可以这样使用:
.button {
@include border(1px, solid, #999);
padding: 0.5rem 0.75rem;
font-size: 14px;
}
如果您不发送任何参数,它将进入其他状态(如上)。如果你发送一个position参数,它就进入if状态。像这样:
.button {
@include border(1px, solid, #999, right);
padding: 0.5rem 0.75rem;
font-size: 14px;
}
此外,请记住可选参数必须位于强制参数之后。这是规定。
我需要一个 SCSS mixin 来制作边框。在这个 mixin 中,$position
变量应该是可选的:
@mixin border($position, $width, $style, $color) {
@if $position {
border-#{$position}: $width $style $color;
} @else {
border: $width $style $color;
}
}
这是必要的,以便我可以在这两种情况下使用它:
.box {
@include border('bottom', 1px, solid, #999) /*with position*/;
}
和
.button {
@include border(1px, solid, #999); /*without position*/
@include border-radius(9999999px);
padding: .5rem .75rem;
font-size: 14px;
}
对于第二种情况,编译器抛出错误:
Mixin border is missing argument $color.
我做错了什么?
您可以为$position 使用默认参数。我使用 false
布尔值作为默认变量。
@mixin border($width, $style, $color, $position: false) {
@if $position {
border-#{$position}: $width $style $color;
} @else {
border: $width $style $color;
}
}
你可以这样使用:
.button {
@include border(1px, solid, #999);
padding: 0.5rem 0.75rem;
font-size: 14px;
}
如果您不发送任何参数,它将进入其他状态(如上)。如果你发送一个position参数,它就进入if状态。像这样:
.button {
@include border(1px, solid, #999, right);
padding: 0.5rem 0.75rem;
font-size: 14px;
}
此外,请记住可选参数必须位于强制参数之后。这是规定。