簡體   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