【问题标题】:Is there a way to use default property value if the variable not used? SCSS如果未使用变量,有没有办法使用默认属性值? SCSS
【发布时间】:2021-04-05 08:16:06
【问题描述】:

首先,我为应用程序创建了 UI/UX,在其中我提取了常用组件、调色板、字体,并将它们与媒体查询一起制作成库。我意识到有些组件本质上是相同的,只是在一些属性上有所不同,例如高度或宽度。所以我制作了可以在旅途中定制的组件样式和组件,所以当涉及到实际的界面实现时,我基本上可以玩 LEGO。

问题在标题中。我可以以某种方式为变量设置默认值吗?因此,当未传入时,我不会收到错误消息,而是显示为默认值?如果是,最简单的方法和最佳做法是什么?

组件 SCSS:

@mixin component($width, $height, $color) {
  .component{
     height: $height;
     width: $width;

     .somethingNested {
        color: $color;
     }
     ...
  }
   @content (if something needs to be overwritten)
}

【问题讨论】:

    标签: css scss-mixins


    【解决方案1】:

    是的,这是可能的。您在参数后添加: value

    @mixin component($width: 80px, $height: 80px, $color: white) {
       ...
    }
    

    提示:mixin 支持位置参数和命名参数。

    // you wanna keep the default $width and $height but change $color
    // with positional argument you have to repeat yourself
    .foo {
      @include component(80px, 80px, pink);
    }
    
    // with named argument, just provide the $color
    . foo {
      @include component($color: pink);
    }
    

    参考:https://sass-lang.com/documentation/at-rules/mixin#optional-arguments

    【讨论】:

    • 谢谢。命名参数似乎是一个优雅的解决方案,我不需要将库直接导入组件,如果我将它们连接到页面的 SCSS 中就足够了。它会找到变量。例如```@mixin name($shadowColorLight: $shadowLight)```会通过页面的SCSS在调色板库中找到$shadowLight。不要因为未定义的变量而引发错误,因为 mixin 本身不会执行,而是在使用时执行。
    猜你喜欢
    • 2013-03-31
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2019-10-14
    • 2016-09-10
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多