xChar
·5 months ago

React + Tailwind CSS 项目,别的语言同理,只需改变 html 标签的 data-theme 属性即可。

import { useEffect } from 'react'
import { useState } from 'react'

export function ThemeToggle() {
  const [theme, setTheme] = useState('light')

  const toggleTheme = () => setTheme((prev) => (prev === 'light' ? 'dark' : 'light'))

  useEffect(() => {
    document.querySelector('html').setAttribute('data-theme', theme)
  }, [theme])

  return (
    <label className="swap swap-rotate">
      <input onClick={toggleTheme} type="checkbox" />
      <span className="i-lucide-sun swap-on size-6" />
      <span className="i-lucide-moon swap-off size-6" />
    </label>
  )
}

如果想记忆用户选择,可以从 localStorage 中获取 theme,并在用户改变时存储该值。

const [theme, setTheme] = useState(localStorage.getItem('theme') ?? 'light')

useEffect(() => {
  // ...
  localStorage.setItem('theme', theme)
}, [theme])
Loading comments...