[英]How can I add a stylesheet dynamically with NextJS?
在我的 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 文件中。
我真的很感激这方面的任何帮助。
虽然可以在您的主要应用程序组件中动态导入 CSS 文件(您可以查看本指南中的示例),但我建议采用不同的解决方案。
在您的应用程序中包含所有样式表,但使其 styles 仅在html
(或body
)元素具有特定 class 时适用。然后您需要做的就是根据用户偏好修改该 class。
// styles.css
body.themeFoo #container {
// some styles...
}
这是暗模式的许多实现,例如在 tailwind CSS 中。我相信这是解决您的问题的更好模式。
next.js 使用 React,所以也许可以尝试使用useState 钩子,或者您可以更改 herf 属性
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>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.