在next.js中使用styled-component以及全局主题切换

使styled-component 像SPA中使用

参考
https://www.w3cschool.cn/styledcomponents/styledcomponents-r9hb38jb.html
https://blog.csdn.net/weixin_44677431/article/details/90339631

主题

_app.js
只加入一个 ThemeProvide 具体在 ThemeProvide 中

import type { AppProps } from "next/app";
import ThemeProvide from "../context/ThemeProvide";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ThemeProvide>
      <Component {...pageProps} />
    </ThemeProvide>
  );
}
export default MyApp;

ThemeProvide

import {
  createContext,
  useState,
  useCallback,
  ReactNode,
  useContext,
} from "react";
import { ThemeProvider } from "styled-components";

export const lightTheme = {
  primary: "#51f",
  fg: "#fff",
  bg: "#000",
  mode: "light",
};

const darkTheme = {
  primary: "#083f2c",
  fg: "#000",
  bg: "#eee",
  mode: "dark",
};

const ThemeContext = createContext<undefined | (() => void)>(undefined);

export const useToggleTheme = () => useContext(ThemeContext);

const ThemeProvide = ({ children }: { children: ReactNode }): JSX.Element => {
  const [theme, setTheme] = useState(lightTheme);

  const toggleMode = useCallback(() => {
    setTheme(({ mode }) => (mode == "dark" ? lightTheme : darkTheme));
  }, []);

  return (
    <ThemeContext.Provider value={toggleMode}>
      <ThemeProvider theme={theme}>{children}</ThemeProvider>
    </ThemeContext.Provider>
  );
};

export default ThemeProvide;
上一篇:baseUI 中 styletron方法 伪类伪元素设置


下一篇:4-3 CSS-IN-JS