如何重用其选择器是通过串联形成的mixin [英] How to re-use a mixin whose selector is formed using concatenation

查看:57
本文介绍了如何重用其选择器是通过串联形成的mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Less中,我可以写:

In Less, I can write:

.outer {  
    .inner {  
        color: red;  
    }  
}

.test {  
    .outer .inner;
}

但是当我写:

.outer {  
    &-inner {  
        color: red;  
    }  
}

.test {  
    .outer-inner;
}

当我删除.test时,.outer-inner输出正确,但是当我重新添加它时,编译器说

When I remove the .test, the .outer-inner output properly, but when I add it back, the compiler says

.outer-inner是未定义的.

.outer-inner is undefined.

反正还有重用.outer-inner的样式吗?

Is there anyway to re-use the styles of .outer-inner?

推荐答案

使用Less,当前无法调用其选择器由串联组成的mixin.但是,对于在编译时使用插值法形成的选择器(也称为动态形成的选择器)来说,这是可能的.

Calling a mixin whose selector is formed by concatenation is currently not possible with Less. However the same is possible for selectors formed at compilation time using interpolation (also referred to as dynamically formed selectors).

以下(内插/动态形成的选择器)可以正常工作.

The below (interpolated/dynamically formed selector) would work fine.

@selector: .box;
@{selector}{
    color: red;
    .child{
        color:blue;
    }
}
.demo{
    .box; /* will create both parent & child */
}
.container{
    &.box{
        background: black;
    }
}
.demo2{
    .container.box;
}

而下面的示例将不起作用.

whereas, the following example will not work.

.container{
    &-box{
        color: blue;
    }
}
.demo2{
    .container-box; /* this will not work */
}


当前,该方案的一种解决方法创建两个单独的Less文件.


Currently, one work-around to the scenario in question is to create two separate Less files.

在第一个文件(test.less)中,添加以下代码并将其编译为CSS文件.

In the first file (test.less) add the below code and compile it into a CSS file.

.outer {  
    &-inner {  
        color: red;  
    }  
}

在第二个文件中,使用(less)指令导入从第一个文件创建的CSS,然后调用/重复使用mixin.

In the second file, import the CSS created from the first file with the (less) directive and then call/re-use the mixin.

@import (less) "test.css";
.test {  
    .outer-inner;
}

注意:如maxim-phases-max的注释中所述,此问题类似于

Note: As mentioned in comments by seven-phases-max, this issue is similar to this item. However both these issues are not the same as extend will not work with both interpolated selector (dynamically formed) and concatenated selector.

选项2:另一个选择是编写具有共同属性的虚拟混入或单独的分离规则集,并像使用它一样使用在下面.

Option 2: Another option would be to write a dummy mixin or a separate detached ruleset with common properties and make use of it like below.

@dummy: {color: red}; // detached ruleset

.outer{
    &-inner{
        @dummy();
    }
}

.test{
    @dummy();
}

.dummy() {color: blue}; // dummy mixin and would produce no extra selector in output as it has parentheses.

.outer{
    &-inner{
        .dummy;
    }
}

.test{
    .dummy;
}

这篇关于如何重用其选择器是通过串联形成的mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆