使用 next-themes 两行代码为 Next.js 项目添加暗黑模式

之前写过文章介绍 React 暗黑模式的实现方式,其原理基本和目前主流的暗黑模式实现方案相似,主要用到的技术有:CSS Variables, 媒体查询, window.matchMedia, React Context 等。但是每个项目都需要重复实现会带来冗余的代码和额外的维护成本。

于是发现社区已有了封装好的方案:next-themes,口号是 Perfect Next.js dark mode in 2 lines of code. 经过试用之后发现其接入简单、功能丰富、支持自定义扩展度高、实现原理基本类似,确实能够快速的为 Next.js 项目添加暗黑模式支持。

本文介绍 next-themes 的使用方式。实现效果可以见在线演示

使用

1. 安装

bash 复制代码
npm install next-themes

2. 在 pages/_app.js 中加入 ThemeProvider

这里就是所谓的"两行代码",只需要引入 ThemeProvider 和使用 ThemeProvider 包裹组件即可。

当然其实更多的自定义样式和样式切换会需要额外的代码,但也可以使用提供的封装好的 useTheme hook 快速实现。

jsx 复制代码
import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider>
      <Component {...pageProps} />
    </ThemeProvider>
  )
}

export default MyApp

3. 基于 data-theme='dark' 属性选择器改变样式

默认情况下,next-themes 会修改 html 元素上的 data-theme 属性,可以轻松地使用该属性来设置样式:

css 复制代码
:root {
  /* Your default theme */
  --background: white;
  --foreground: black;
}

[data-theme='dark'] {
  --background: black;
  --foreground: white;
}

4. 使用 useTheme 获取当前主题和改变主题

jsx 复制代码
import { useTheme } from 'next-themes'

const ThemeChanger = () => {
  const { theme, setTheme } = useTheme()

  return (
    <div>
      The current theme is: {theme}
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
    </div>
  )
}

Tailwind CSS 中使用方式

TailWind CSS 中是基于 dark: 来切换暗黑模式样式的,next-themes 也可以结合 TailWind CSS 一起使用。

实现效果可以看在线演示

1. 将 Tailwind 的暗黑模式配置为基于 class

javascript 复制代码
// tailwind.config.js
module.exports = {
  darkMode: 'class'
}

2. 将 data-attribute 方式改为 class

jsx 复制代码
// pages/_app.js
<ThemeProvider attribute="class">

3. 基于 dark: 来切换暗黑模式下的样式

jsx 复制代码
<h1 className="text-black dark:text-white">

更多使用方式可见next-themes 项目文档

参考链接

相关推荐
tedcloud12317 分钟前
Impeccable 部署指南:开源前端设计工具 Linux 环境搭建实践
linux·运维·服务器·前端·人工智能·开源
默_笙26 分钟前
🚩 React + TypeScript 的 Props 通信,我从"把事件对象传给父组件"进化到了"只传值"
前端·javascript
渣波29 分钟前
赋予 React “多线程”:Hooks + Web Worker 并发计算架构深度解析
前端·javascript
光影少年31 分钟前
Codex 斜杠指令体系与业务场景调度实战
前端·react.js·reactivex
90后的晨仔31 分钟前
uni-app中如何跳转?
前端
Y3815326621 小时前
SERP API 请求体 Gzip 压缩优化实战:大数据量降带宽 80%
开发语言·前端·php
踩着两条虫2 小时前
VTJ.PRO AI Agent 技术白皮书
前端·vue.js·低代码
子兮曰2 小时前
解剖 Claude Code:从入口架构逆向工程看 AI 编程工具的信任边界设计
前端·后端·claude
Darling噜啦啦3 小时前
别再逐层传 Props 了!useContext + 自定义 Hook 彻底搞定 React 跨层通信
react.js
先吃饱再说3 小时前
层层传递太“痛”了:useContext 给 React 组件装了个“无线遥控器”
前端·react.js·前端框架