繁体   English   中英

SASS 在 Next.JS CSS 模块中无法正常工作

[英]SASS not working properly within Next.JS CSS modules

这是我第一次使用 Next.JS 的 CSS 模块,它们非常有用。

但是当我尝试将 styles 应用于子元素时,我遇到了一种奇怪的行为。

例如,如果我有以下 HTML

<Offcanvas show={menu} onHide={closeMenu} className={styles.mobile_menu}>
    <Offcanvas.Header closeButton className={styles.mobile_menu_header}>
        <Offcanvas.Title className={styles.mobile_menu_title}>
            <h1>Menu</h1>
        </Offcanvas.Title>
    </Offcanvas.Header>
    <Offcanvas.Body>
        <ul className="list-unstyled">
            { links.map((link, key) => (
                <li key={"nav-link-" + key} className="mb-3">
                    <Link href={link.href} className={[styles.link, router.pathname == link.href ? "active" : ""].join(" ")}>{ link.label }</Link>
                </li>
            )) }
        </ul>
    </Offcanvas.Body>
</Offcanvas>

而这个 SCSS

.mobile_menu {
    background-color: rgb(57, 70, 78) !important;
    color: #fff !important;
}

.mobile_menu_header {
    border-bottom: solid 1px rgb(148, 162, 170);

    button.btn-close {
        filter: brightness(0) invert(1) !important;
        opacity: 1 !important;
        width: 1.6rem !important;
        height: 1.6rem !important;
        background-size: 100% !important;
    }
}

.mobile_menu_title {
    h1 {
        font-size: 3.2rem;
    }
}

.link {
    color: #fff;
    text-transform: uppercase;
    font-size: 1.7rem;
    transition: color 0.3s ease-in-out;

    &.active {
        border-bottom: solid 1rem rgb(148, 162, 170) !important;
    }

    &:hover {
        color: rgb(148, 162, 170);
    }
}

应用于button.btn-close的属性(通过将closeButton标志添加到Offcanvas.Header自动生成)未应用,与active class 的链接也没有预期的底部边框。

所以这让我觉得 Next.JS 的 CSS 模块中的 SASS 没有使用嵌套/子/选择器。 但是,由于某种原因, .mobile_menu_title中的h1被设置了样式,并且当我尝试从选择器中删除.btn-close (仅保留button )时,它被应用了!

那么,这是错误还是我不知道的事情? 使用 SASS 的嵌套 styles 仅适用于“纯”元素,不适用于具有类/ID 的选择器。

有人可以帮我弄这个吗?

谢谢!

注意:我使用的是 react-bootstrap package。

那么,你可以做的是以下

在您的 JavaScript 文件中


...

<Offcanvas.Header closeButton className={styles.mobile_menu_header}>

  ...

</Offcanvas.Header>

...

在你的样式文件中

.mobile_menu_header {
  border-bottom: solid 1px rgb(148, 162, 170);
  :global {
    button.btn-close {
      filter: brightness(0) invert(1) !important;
      opacity: 1 !important;
      width: 1.6rem !important;
      height: 1.6rem !important;
      background-size: 100% !important;
    }
  }
}

为什么这个?

通过添加:global规则,你基本上是在告诉你的 React 应用程序:“在计算出class 名称的元素中mobile_menu_header (实际的 class 名称将类似于index_mobile_menu_header_xxxxxxxx ),找到名称为 class 的元素btn-close并应用样式指定的”。

像您所做的那样,将所有内容包装在mobile_menu_header中,有助于避免覆盖整个应用程序中的btn-close并让它们在此组件中被覆盖。

当覆盖 CSS 库的唯一方法是自己覆盖 styles 时,这可能是一种适应策略(因此,如果您不能通过样式组件或主题设置等其他方式自定义库),但您还需要面对 CSS模块(导致名称类似于而不仅仅是 class 名称)。

暂无
暂无

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

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