【问题标题】:How can I add a stylesheet dynamically with NextJS?如何使用 NextJS 动态添加样式表?
【发布时间】:2023-01-29 17:35:54
【问题描述】:

在我的 nextJS 应用程序中,我需要根据从数据库接收到的用户偏好动态加载样式表。

因此,在我的页面中,我将其添加到 Head (next/head) 中,如下所示:

<Head>
<link rel="stylesheet" href={`/fonts/${type}/stylesheet.css`}></link>
</Head>

但是,这在开发模式的控制台中给我一个警告:

Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="/fonts/cal/stylesheet.css"). Use Document instead. 
See more info here: https://nextjs.org/docs/messages/no-stylesheets-in-head-component

样式表本身包含字体:

@font-face {
  font-family: "Cal Sans";
  src: url("CalSans-SemiBold.woff2") format("woff2"),
    url("CalSans-SemiBold.woff") format("woff");
  font-weight: 600;
  font-style: normal;
  font-display: swap;
}

由于用户的首选项存储在数据库中,并且我通过查询收到此值,因此我不知道如何将其添加到 Document.js 文件中。

我真的很感激这方面的任何帮助。

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    虽然可以在您的主要应用程序组件中动态导入 CSS 文件(您可以查看示例 in this guide),但我建议采用不同的解决方案。

    在您的应用程序中包含所有样式表,但使其样式仅在html(或body)元素具有特定类时应用。然后您需要做的就是根据用户偏好修改该类。

    // styles.css
    body.themeFoo #container {
      // some styles...
    }
    

    这是暗模式的实现方式,例如在顺风 CSS 中。我相信这是解决您的问题的更好模式。

    【讨论】:

    • 这听起来很有趣。但是,如果我包括所有样式表,它不会增加页面大小吗?
    • 是的,这可能是一个合理的担忧。取决于您拥有多少个不同的样式表以及它们有多大。但您可能应该衡量它对性能的影响,因为它可以忽略不计。
    • 我正在为一个网络应用程序按需加载 Google 字体样式表,用户可以在其中从 Google 字体中选择任何字体。预先加载所有这些是不可行的。
    【解决方案2】:

    next.js 使用 React,所以可以试试 useState hook 或者你可以更改 herf 属性

    【讨论】:

      【解决方案3】:
      import { Html, Head, Main, NextScript } from 'next/document'
      
      export default function Document() {
        return (
          <Html>
            <Head>
              <link rel="stylesheet" href="..." />
            </Head>
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-24
        • 1970-01-01
        • 2017-11-16
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        相关资源
        最近更新 更多