sass - 创建一个 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);
}
然而,这带来了两个问题:
variable-exists
期望传入一个字符串。- 如果
$component-button-primary-color
不存在,则编译失败。
我尝试通过传入一个字符串来调用该函数,因此
.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
可以看到这里。但这带来了很多样板,需要大量的上下文切换,因为您无法在一行中找到所需的信息。
任何想法?
解决方案
您可以使用可选参数来获得所需的结果。必需参数必须在可选参数之前。
@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);
}
推荐阅读
- mysql - 选择具有 where 条件的联合,而列具有不同的名称
- security - laravel 中的 Ckeditor 安全问题
- c++ - ICPC:使用带有 icpc 的 std::map 编译 C++ 文件时,“标识符“_Node_allocator”未定义”
- docker - 无法在 Docker for Windows 上访问 RabbitMQ
- mysql - 传递参数是 mysql ,过程之后的字段
- angular - 在 Angular 6 中选择带有 RxJS 的状态不起作用
- php - 使用 codeigniter 从数据库中获取数据
- c++ - 检测 C++ 中的 DST 更改
- svg - SVG定义继承
- c# - MigraDoc 和 .NET Core 2.0