首页 > 解决方案 > 创建一个 SASS 函数以回退到一个值

问题描述

我想创建一个获取 2 个变量作为输入的函数,如果第一个变量存在,则返回该变量,如果不存在,则返回后备值。

我正在尝试这个

@function component-token($token-name, $fallback) {

  @if variable-exists($token-name) {
    @return $token-name;
  } 

  @return $fallback;
}

我想用它作为

.my-class {
  color: component-token($component-button-primary-color,  $color-primary-base);
}

然而,这带来了两个问题:

我尝试通过传入一个字符串来调用该函数,因此

.my-class {
  color: component-token(component-button-primary-color,  $color-primary-base);
}

但这让我color成为了 string component-button-primary-color,这当然不是我想要的。

为了提供一些背景信息,我们正在准备一个多品牌项目,我们希望我们的 CSS 有一组基本值,但每个值都应该可以被品牌覆盖。

在上面的例子中,我们可以假设一个品牌总是有$color-primary-base. 但是品牌也可以定义$component-button-primary-color变量,然后它应该覆盖值。

我们的第一种方法是与!default可以看到这里。但这带来了很多样板,需要大量的上下文切换,因为您无法在一行中找到所需的信息。

任何想法?

标签: sass

解决方案


您可以使用可选参数来获得所需的结果。必需参数必须在可选参数之前。

@function button-color($color-primary-base, $color-primary-button: null) {

    @if $color-primary-button != null {
        @return $color-primary-button;
    }

    @return $color-primary-base;
}

我更改了代码/名称以匹配您的用例:更改按钮的颜色。

呼叫者,召集者:

$customer-color-primary-base : red;
$customer-color-primary-button: green;

button {
    color: button-color($customer-color-primary-base, $customer-color-primary-button);
}

如您所见,它不需要字符串作为参数。

您可以尝试将参数保留为空或根本不提供可选参数:

$customer-color-primary-button: null;

或者

color: button-color($customer-color-primary-base);

它确实允许您稍后更改变量(动态道具是不可能的,但可以首先使用空值对其进行 decalare):

$customer-color-primary-base : red;
$customer-color-primary-button: null;
$customer-color-primary-button: green;

.button {
    color: button-color($customer-color-primary-base, $customer-color-primary-button);
}

推荐阅读