Next.js 项目中更换主题(尤其是使用 Tailwind CSS 或其他 UI 框架时),通常有以下几种方式:


✅ 方法一:使用 Tailwind CSS 主题配置(推荐)

如果你的 Next.js 项目使用了 Tailwind CSS,可以通过修改 tailwind.config.js 来切换主题。

步骤:

  1. 打开 tailwind.config.js 文件。

  2. theme 中定义多个主题(例如深色/浅色):

    // tailwind.config.js
    module.exports = {
    content: [
     "./pages/**/*.{js,ts,jsx,tsx}",
     "./components/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
     extend: {
       colors: {
         // 浅色主题
         light: {
           primary: '#3b82f6',
           background: '#ffffff',
           text: '#1f2937'
         },
         // 深色主题
         dark: {
           primary: '#60a5fa',
           background: '#111827',
           text: '#f9fafb'
         }
       }
     },
    },
    plugins: [],
    }
  3. 在你的组件中通过类名切换主题:

    // App.jsx 或 _app.js
    import { useState } from 'react';

export default function MyApp({ Component, pageProps }) { const [isDark, setIsDark] = useState(false);

return ( <div className={isDark ? 'dark' : ''}> <Component {...pageProps} />