深色模式
規則
- 使用
next-themes — 將應用程式包裝在 <ThemeProvider attribute="class" defaultTheme="system"> 中
- CSS 變數定義顏色 — 在
:root(淺色)和 .dark(深色)中定義,並以 var(--background) 方式引用
- 系統偏好偵測:
defaultTheme="system" 會遵從 prefers-color-scheme 媒體查詢
- 主題切換元件:在淺色、深色與系統之間循環 — 使用
next-themes 的 useTheme() hook
- Tailwind 整合:在 tailwind 配置中啟用
darkMode: "class",並使用 dark: 前綴進行覆寫
- 水合修復:僅在
useEffect 後掛載主題切換元件,或使用 suppressHydrationWarning 來避免水合錯誤
- 持久化:
next-themes 將偏好儲存在 localStorage 中,並以 class 的形式套用至 <html> 元素
- 過渡效果:在 body 上添加
transition-colors duration-200 以實現流暢的主題切換
模式
import { ThemeProvider } from "next-themes";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
</ThemeProvider>
</body>
</html>
);
}
"use client";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return (
<button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
{theme === "dark" ? "☀️" : "🌙"}
</button>
);
}
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
}
避免
- 將顏色硬編碼而非使用 CSS 變數 — 這會導致無法進行主題切換
- 忘記在
<html> 上使用 suppressHydrationWarning — 會造成水合錯誤
- 主題閃爍:確保
next-themes 的腳本在網頁繪製前執行(預設即會這樣做)
- 僅支援淺色/深色而缺少系統選項 — 應尊重使用者的作業系統偏好