css 模块中未生成的类名选择器

问题描述 投票:0回答:2

假设我们有一个第三方

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;
  }
}

然后将类添加到Card

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

上面将不起作用,因为它为

CardBody
创建了一个生成的类,如
CardBody_sjkdh43
。有没有办法在模块中选择非生成的类名?或者这只能以旧时尚的方式使用样式表?

演示沙盒

css css-modules react-css-modules
2个回答
13
投票

答案是使用 CSS 模块中的

:global()
选择器。

了解更多信息:异常 - CSS 模块

代码示例:

<div class={styles.myClass}>
    <SomeComponentWithOwnCss />
</div>

输出:

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

和CSS:

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

此处的工作示例:codesandbox


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>
© www.soinside.com 2019 - 2024. All rights reserved.