带变量覆盖的继承

时间:2015-03-09 18:54:30

标签: less

我已经定义了一个使用变量.class

的类@var
@var: 'value';

.class {
    property: @var;
    // and much more stuff [...]
}

现在我想继承.class并在同一时间更改@var的值,如下所示:

.another-class {
    @var: 'another-value';
    .class;
}

但似乎未采用新值another-value。如何在不更改.class的情况下实现此目的?

2 个答案:

答案 0 :(得分:1)

我在最简单的情况下建议只是一个参数 mixin,例如:

@var: value;

.mixin(@parameter: @var) {
    property: @parameter;
}

.class {
    .mixin();
}

.another-class {
    .mixin(another-value);
}

(除非你需要覆盖太多变量以使mixin变得过于冗长......但在这种情况下,重新使用样式的想法本身就会有缺陷。选择更好的解决方案可能过于可靠真正的代码(.class到底是什么以及它在CSS的上下文中实际做了什么)。

关于#2435的一般类似用例的讨论,detailed why对{{3}}的解释实际上以这种方式工作({{1} }}> global scope)以及通过变量覆盖而不是显式参数传递和/或显式CSS属性覆盖来参数化mixin的各种优缺点的其他见解。

答案 1 :(得分:0)

好的,这个问题似乎与" Can I override global variables from the calling scope"重复。我在评论中找到了答案(https://gist.github.com/seven-phases-max/9473260),但这会稍微改变一下原来的类:

@var: 'value';

.lib() {
    .class() {
        property: @var;
        // and the rest of `.class`
    }
}

.class {
    .lib.class();
}

.another-class {
    @var: 'another-value';
    .lib.class();
}