CSS 模块中的非生成类名选择器

10
假设我们有一个第三方的 CardComponent 组件,就像这样。
<Card title="This is a title in the header">This is text in the body</Card>

并且这将以纯HTML呈现

<div class="Card">
  <div class="CardHeader"></div>
  <div class="CardBody"></div>
</div>

我在使用 CSS 模块来进行样式设计(在这种情况下是 SCSS)。

.customCard {
  .CardBody {
    color: red;
  }
}

然后将该类添加到卡片中

import styles from ...
...
<Card className={styles.customCard} ...>...</Card>

上面的方法行不通,因为它会为 CardBody 创建一个生成的类,例如 CardBody_sjkdh43。在模块中是否有一种选择非生成类名的方法?或者只能以传统方式使用样式表来实现? 演示沙盒: Demo SandBox

请问您能否分享演示文稿,以便我可以开始工作? - Pritesh
添加了一个沙盒 :) - Stutje
看起来你只能访问我们作为props传递的customCard类,没有其他的 :) - Pritesh
2个回答

16
答案是在CSS模块中使用:global()选择器。
更多信息请参考:Exceptions - CSS Modules
示例代码:
<div class={styles.myClass}>
    <SomeComponentWithOwnCss />
</div>

输出:

<div class="myClass_s4jkdh3">
    <div class="SomeComponentWithOwnCss"></div>
</div>  

还有CSS:

.myClass div:global(.SomeComponentWithOwnCss) {
    background-color: red;
}

这里有一个工作示例:codesandbox

很好。简单明了。相当直接。非常感谢你。 - Iharob Al Asimi

1
你可以尝试使用SCSS来实现更方便的方法:
.parent :global {
  .non-cssmodule-class {
    color: red;
  }
}

<div className={styles.parent}>
  <div className="non-cssmodule-class" />
</div>

输出:

<style>
  .filename-parent__7MR41 .non-cssmodule-class { color: red; }
</style>
<div class="filename-parent__7MR41">
    <div class="non-cssmodule-class"></div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接