dark mode
Install next-themes
Section titled “Install next-themes”pnpm add next-themesCreate a theme provider
Section titled “Create a theme provider”"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
Section titled “Wrap your root layout ”将 ThemeProvider 添加到根布局中,并将 suppressHydrationWarning 属性添加到 html 标签中。
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
Section titled “Add a mode toggle ”在您的网站上添加一个模式切换按钮,用于在浅色模式和深色模式之间切换。
"use client"
import * as React from "react"import { Moon, Sun } from "lucide-react"import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"
export function ModeToggle() { const { setTheme } = useTheme()
return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="outline" size="icon"> <Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" /> <Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" /> <span className="sr-only">Toggle theme</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => setTheme("light")}> Light </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("dark")}> Dark </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("system")}> System </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> )}