如何在next js中动态更改全局样式表

Roy*_*ter 5 reactjs next.js

我有两个 CSS 文件,一个用于浅色主题,另一个用于深色主题。如何动态改变样式表?

这是我当前在 __app.js 中使用的代码

import React, { useState, useEffect } from "react";
import "../styles/globals.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import { ThemeContext } from "../context/ThemeContext";

function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    if (theme == "dark") {
      import("primereact/resources/themes/arya-blue/theme.css");
    }
    if (theme == "light") {
      import("primereact/resources/themes/saga-blue/theme.css");
    }
  }, [theme]);

  return (
    <ThemeContext.Provider value={[theme, setTheme]}>
        <Component {...pageProps} />
    </ThemeContext.Provider>
  );
}

export default MyApp;

Run Code Online (Sandbox Code Playgroud)

此代码可以从浅色主题切换到深色主题,但无法从深色主题切换到浅色主题。他们有更好的方法吗?

Roy*_*ter 4

我通过这篇博客文章解决了这个问题,但存在一些差异。

1. 创建一个新的 Themes.js 文件,其中包含深色模式和浅色模式样式


const DarkTheme = () => {
  return (
    <style jsx global>
      {`
       Copied here the entire dark mode style sheet from node modules (around 5000 lines)
      `}
    </style>
  );
};

const LightTheme = () => {
  return (
    <style jsx global>
      {`
       Copied here the entire light mode style sheet from node modules (around 5000 lines)
      `}
    </style>
  );
};

export default function Theme({ theme }) {
  if (theme == "dark") {
    return <DarkTheme />;
  }
  return <LightTheme />;
}

Run Code Online (Sandbox Code Playgroud)

2. 在 __App.js 文件中使用 Themes 组件,并通过本地存储实现上下文和主题持久化:


import React, { useState, useEffect } from "react";
import Head from "next/head";
import "../styles/globals.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import { ThemeContext } from "../context/ThemeContext";
import Theme from "../themes/Theme"; //imported newly created theme file
import PrimeReact from "primereact/api";

function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState((typeof window !== "undefined" && localStorage.getItem("theme")) || "light");

  useEffect(() => {
    typeof window !== "undefined" && localStorage.setItem("theme", theme);
  }, [theme]);

  return (
    <>
      <ThemeContext.Provider value={[theme, setTheme]}>
        <Theme theme={theme} /> {//This Component provides dynamic global styles}
          <Component {...pageProps} />
      </ThemeContext.Provider>
    </>
  );
}

export default MyApp;
Run Code Online (Sandbox Code Playgroud)