动态插入 class 名称并将其作为变量传递

Dynamically interpolate class name and pass it as variable

我有以下混入:

@mixin indication-circle($color-class, $with-background: true) {
  display: inline;
  border-radius: 15px;
  padding: 0rem 0.75rem;

  &::before {
    content: "\A";
    width: 0.4rem;
    height: 0.4rem;
    margin-left: 0.25rem;
    border-radius: 50%;
    display: inline-block;
  }

  @if $color-class=='success' {
      &::before {
        background: #87F437;
        opacity: 1;
      }

    @if $with-background {
      background-color: #87F43733;
    }
  }

  @if $color-class=='info' {
    &::before {
      background: #807C7E;
      opacity: 1;
    }


    @if $with-background {
      background-color: #E9E7EA;
    }
  }

  @if $color-class=='warning' {
    &::before {
      background: #FFBE43;
      opacity: 1;
    }

    @if $with-background {
      background-color: #FFBE4333;
    }
  }

  @if $color-class=='danger' {
    &::before {
      background: #F43E37;
      opacity: 1;
    }


    @if $with-background {
      background-color: #F43E3733;
    }
  }
}

这个 mixin 在整个应用程序中使用,并为您提供这个(有或没有背景):

@include 使用这个 mixin 时,我如何避免过于明确? (当前用法,重复每个选项...):

//Selectors...
&.success {
  label {
    @include indication-circle('success', false);
  }
}
//Same for `&.info`, `&.warning`, `&.danger`...

我能否以某种方式插入 class 名称并将其作为变量发送?还是处理这些动态样式的更好方法?

伪:

  label {
    @include indication-circle(#{parentNode.class}, false);
  }

通过使用 @eachmapslist 的 SASS 代码变得如此小。

https://sass-lang.com/documentation/at-rules/control/each

https://sass-lang.com/documentation/values/lists

https://sass-lang.com/documentation/values/maps

在下面的代码中,$indication-colors 是一个地图,它保留了每个州的两种颜色。地图值可以通过 map-get 函数访问。在此代码中,地图值为 list,具有两个颜色值。

最后一部分使用 @each$indication-colors 映射的每个键生成 class。

$indication-colors: (
    success:    (#87F437, #87F43733),
    info:       (#807C7E, #E9E7EA),
    warning:    (#87F437, #FFBE4333),
    danger:     (#F43E37, #87F43733),
);


@mixin indication-circle($color-class, $with-background: true) {
    display: inline;
    border-radius: 15px;
    padding: 0rem 0.75rem;
    
    $configs: map-get($indication-colors, $color-class);
    
    &::before {
        content: "\A";
        width: 0.4rem;
        height: 0.4rem;
        margin-left: 0.25rem;
        border-radius: 50%;
        display: inline-block;
        background: nth($configs, 1);
        opacity: 1;
    }
    
    
    @if $with-background {
        background-color: nth($configs, 2);
    }
}

@each $states in $indication-colors {
    .parent-class{
        $key: nth($states, 1);
        &.#{$key} {
            label {
                @include indication-circle($key, true);
            }
        }
    }
}