在 Next.js + Tailwind 中使用暗黑模式的简单方法
昨天我在整理我的个人网站,很想添加一个暗黑模式切换开关。
我之前已经把网站改用 Tailwind 了,现在该如何启用暗黑模式呢?
很简单:Tailwind v2 内置了暗模式(https://tailwindcss.com/docs/dark-mode)。
要切换暗黑模式,您需要darkMode: 'class'
在 中添加tailwind.config.js
。
此配置意味着dark
将在标签中添加一个名为 的类<html>
。
一旦该类处于活动状态,您的dark:{class}
类也将处于活动状态。
为了将此功能与 Next.js 链接起来,我使用了轻量级的next-themes库(https://github.com/pacocoursey/next-themes)。
安装此库后,只需更改_app.js以包含ThemeProvider:
import { ThemeProvider } from 'next-themes'
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider attribute="class">
<Component {...pageProps} />
</ThemeProvider>
)
}
export default MyApp
包括这attribute="class"
一点非常重要,因为这会告诉库使用 Tailwind 暗主题类。
对于切换按钮,我使用了以下内容:
import {useTheme} from 'next-themes'
const {theme, setTheme} = useTheme()
<button
aria-label="Toggle Dark Mode"
type="button"
className="p-3 h-12 w-12 order-2 md:order-3"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
代码示例dark:{class}
,亮模式下使用紫色背景颜色,暗模式下使用深灰色:
<nav className="fixed bg-purple dark:bg-darkgrey h-16 w-full z-50">
就是这样!点击按钮即可切换主题。
在线示例:https://www.thomasledoux.be/
Github 源码:https://github.com/thomasledoux1/website-thomas
灵感来源:https://leerob.io