【问题标题】:What is the cause of this failure to make a SCSS mixin with an optional parameter?使用可选参数制作 SCSS mixin 失败的原因是什么?
【发布时间】:2020-06-23 20:59:33
【问题描述】:

我需要一个 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.

我做错了什么?

【问题讨论】:

    标签: css sass mixins


    【解决方案1】:

    您可以使用 $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;
    }
    

    如果不发送任何参数,则进入 else 状态(如上)。如果你发送一个位置参数,它会进入 if 状态。像这样:

    .button {
      @include border(1px, solid, #999, right);
      padding: 0.5rem 0.75rem;
      font-size: 14px;
    }
    

    另外,请记住可选参数必须在强制参数之后。这是一条规则。

    【讨论】:

      猜你喜欢
      • 2012-02-24
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多