全栈开发个人博客04:深色模式

107 阅读1分钟

Shadcn/ui 是一个现代化的 React UI 组件库,旨在提供可自定义、高质量、无依赖的用户界面组件。它利用 Tailwind CSS 和 React 的灵活性,提供了一组易于使用、响应式且可扩展的 UI 组件,帮助开发者快速构建美观且功能丰富的应用界面,同时保持设计的一致性和灵活性。

1. 配置深色模式

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

2.切换模式

  • 使用 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>
  )
}