简体   繁体   English

如何基于布尔prop在ReactJS中有条件地应用嵌套的SCSS类?

[英]How to conditionally apply nested SCSS classes in ReactJS based on a boolean prop?

I have a sidebar navigational element that I'm attempting to apply SCSS styles to based on the position of the element, in React. 我有一个侧边栏导航元素,我试图在React中根据元素的位置应用SCSS样式。 This is what I currently have for the combination of CSS classes imported from a module: 这是我目前用于从模块导入的CSS类的组合:

styles.main,
styles[position],
isOpen ? styles.opened : styles.closed,

The snippet from the SCSS file: 来自SCSS文件的片段:

.right {
  top: 0;
  right: 0;

  .opened {
    visibility: visible;
  }

  .closed {
    visibility: hidden;
  }
}

I'm trying to figure out how to have the SCSS styles be applied correctly. 我正在试图弄清楚如何正确应用SCSS样式。 The elements are inheriting the .main class and the root selector for .right (containing the top and right attributes), but not the ones for .right.opened and .right.closed . 的元件被继承.main类和根选择.right (包含topright属性),而不是那些用于.right.opened.right.closed

Any help or pointers as to where I'm going wrong would be MUCH appreciated. 关于我出错的地方的任何帮助或指示都会非常感激。 Thank you very much! 非常感谢你!

You don't have to inherit the styles, but compose them. 您不必继承样式,而是组合它们。 Instead of having: 而不是:

.right {
  top: 0;
  right: 0;

  .opened {
    visibility: visible;
  }

  .closed {
    visibility: hidden;
  }
}

you have to do: 你必须做:

.right {
  top: 0;
  right: 0;

  &__opened {
    visibility: visible;
  }

  &__closed {
    visibility: hidden;
  }
}

Then, you will apply classes like isOpen ? styles.right__opened : styles.right__closed 然后,您将应用像isOpen ? styles.right__opened : styles.right__closed这样的类isOpen ? styles.right__opened : styles.right__closed isOpen ? styles.right__opened : styles.right__closed . isOpen ? styles.right__opened : styles.right__closed

You can check my demo . 你可以查看我的演示

使用classnames实用程序,它是当前推荐的在ReactJs中处理条件CSS类名的方法。

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

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