javascript - 从 CSS 模块中访问全局类

标签 javascript css reactjs sass css-modules

我正在开发一个使用 ReactJS 和 CSS 模块的元素,每个 React 组件都有相应的 SASS 文件。

在编写 CSS 时,每个类都会附加“三重下划线随机字符串”,例如.myClass__e7G3A

我的应用程序根据滚动位置将一个类(top'或'down')附加到 body 标签,我希望我的组件对此做出响应。

我遇到的问题是,如果我在 CSS 模块中添加 .top.down,那么它也会将唯一标识符附加到该类的末尾。

例如

JSX:

<div className={styles.main}>
  Main content goes here.
</div>

呈现的 HTML:

<body class="top">
  <div class="main___iZy2A">
    Main content goes here.
  </div>
</body>

SASS 文件:

.top .main {
  margin-top: 0;
}
.down .main {
  margin-top: 100px;
}

编译后的 CSS:

.top___Gvf3S .main___iZy2A {
  margin-top: 0;
}
.down___kpd3S .main___iZy2A {
  margin-top: 100px;
}

所需的 CSS 结果:(.top.down 没有唯一标识符)

.top .main___iZy2A {
  margin-top: 0;
}
.down .main___iZy2A {
  margin-top: 100px;
}

我确定我只是缺少一个简单的标识符或可以实现此目的的东西。

希望能帮到你。谢谢。

最佳答案

使用:global在选择器上:

:global(.top) .main___iZy2A {
  margin-top: 0;
}
:global(.down) .main___iZy2A {
  margin-top: 100px;
}

或者 :global:local 的组合,如果你有多个全局选择器:

:global .top .top--left :local .main___iZy2A {
  margin-top: 0;
}
:global .down .down--right :local .main___iZy2A {
  margin-top: 100px;
}

关于javascript - 从 CSS 模块中访问全局类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40630248/

相关文章:

javascript - 如何永久阻止在 onbeforeunload 上分配函数的能力

javascript - 链接页面的 HTML/JS 解释对话框

html - 如何让一个 div 停留在页面底部,这样访问者就无法滚动到它?

javascript - 如何使用 jQuery 实时检查 html 中的元素插入情况。

javascript - 在 Zapier 中使用 Array.find 时遇到问题 - 无法读取未定义的属性

reactjs - 如果文本很长,React 'react-data-table-component' 悬停时不显示工具提示

reactjs - 将组件包装在函数、事件处理和状态 Hook 内的组合表现出意外

reactjs - React - 激活 onClick 函数会引发 'Cannot read property' 错误

javascript - 使用 cookie 显示 div

css - Bootstrap 3 导航中的居中 Logo