Docs
Next.js
Next.js
将夜间模式添加到你的下一个应用。
夜间模式
¥Dark mode
安装 next-themes
¥Install next-themes
从安装 next-themes
开始:
¥Start by installing next-themes
:
pnpm add next-themes
创建主题提供程序
¥Create a theme provider
components/theme-provider.tsx
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
封装根布局
¥Wrap your root layout
将 ThemeProvider
添加到你的根布局。
¥Add the ThemeProvider
to your root layout.
app/layout.tsx
import { ThemeProvider } from "@/components/theme-provider"
export default function RootLayout({ children }: RootLayoutProps) {
return (
<>
<html lang="en" suppressHydrationWarning>
<head />
<body>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</body>
</html>
</>
)
}
添加模式切换
¥Add a mode toggle
在你的网站上放置一个模式切换按钮,以在明夜间模式之间切换。
¥Place a mode toggle on your site to toggle between light and dark mode.