简体   繁体   English

SASS中的动态类名称

[英]Dynamic class names in SASS

I am new to SASS. 我是SASS的新手。 I want to create an element with a dynamic class name that I can then easily control in my SASS. 我想用动态类名创建一个元素,然后可以在我的SASS中轻松控制它。 Something like one of the two psuedo examples below. 类似于下面的两个伪示例之一。 How do I do this in SASS? 我该如何在SASS中执行此操作? Thanks! 谢谢!

EXAMPLE 1: 示例1:

--- React JS --- -React JS-
<div className={this.state.onClick ? "menu-on" : "menu-off"}></div>

--- SASS --- --- ASS ---

.menu-{x} {
  x = "on": {
    background-color: blue;
  }
  x = "off": {
    background-color: red;
  }
}

EXAMPLE 2: 范例2:

--- React JS --- -React JS-

<div className={"menu " + (this.state.onClick ? "on" : "off")}></div>

--- SASS --- --- ASS ---

.menu {
  .on {
    background-color: blue;
  }
  .off {
    background-color: red;
  }
}

You can't control SASS from React since it's essentially static once you've compiled it to CSS. 您无法从React控制SASS,因为一旦将其编译为CSS,它实际上是静态的。

However, I think your second example will work if you change the SASS to the following: 但是,我认为如果将SASS更改为以下内容,第二个示例将起作用:

.menu {
  &.on {
    background-color: blue;
  }
  &.off {
    background-color: red;
  }
}

Which will compile to the following CSS: 它将编译为以下CSS:

.menu.on {
    background-color: blue;
}
.menu.off {
    background-color: red;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM