全栈开发个人博客04:深色模式
cz2025.05.26 08:19

1. 为什么选择shadcn/ui作为UI库

  • 非Npm包,组件代码按需添加,可以自由修改
  • 匹配tailwindcss 语法,主题定制极简,通过css变量即可全局调整颜色、间距等

2. 配置深色模式

  • 参考官方文档,使用next-themes,配置深色模式,https://ui.shadcn.com/docs/dark-mode/next
  • 原理就是切换深色模式时,给html添加dark类名,然后通过css变量调整样式,比如--foreground--background

3.切换模式

  • 使用 next-themes提供的useTheme hook,可以获取当前主题,并切换主题
// src/components/ThemeModeToggle.tsx
'use client'

import { Moon, Sun } from 'lucide-react'
import { useTheme } from 'next-themes'

export default function ThemeModeToggle() {
  const { theme, setTheme } = useTheme()

  return (
    <div
      className="hover:bg-accent hover:text-accent-foreground text-foreground relative flex size-8 cursor-pointer items-center justify-center transition-colors"
      onClick={() => (theme === 'light' ? setTheme('dark') : setTheme('light'))}
    >
      <Sun className="size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
      <Moon className="absolute left-1/2 top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
    </div>
  )
}

Comments