NextJs设置主题

安装依赖

pnpm add next-themes

页面配置

ts
1// app/layout.jsx
2import { ThemeProvider } from 'next-themes'
3
4export default function Layout({ children }) {
5  return (
6    <html suppressHydrationWarning>
7      <head />
8      <body>
9        <ThemeProvider>{children}</ThemeProvider>
10      </body>
11    </html>
12  )
13}

通过设置 theme 切换主题

ts
1import { useTheme } from "next-themes";
2const { theme, setTheme } = useTheme();
3onClick={() => setTheme(theme === "light" ? "dark" : "light")}