繁体   English   中英

在 React 中动态切换 CSS 文件

[英]Dynamically switch CSS files in React

I have 2 css files: light.css and dark.css , also have a ThemeSwitch component which represents the select element, this element has handler for handling change of value (the value is either light or dark ). 问题是:有什么方法可以根据 ThemeSwitch 值包含这些 css 文件之一:如果值是light的 - 导入/包括light.css ,如果值是dark的 - 然后导入/包括暗的dark.css (像一个开关)

您可以使用 react-lazy 或 react-suspense 库来有条件地更改组件或 CSS 文件。

下面是 react-lazy 库的示例

import React, { useLayoutEffect, useState } from "react";

const Theme1 = React.lazy(() => import("./Theme1"));
const Theme2 = React.lazy(() => import("./Theme2"));
const THEME_1 = "1";
const THEME_2 = "2";
export const ThemeSelector = ({ children }) => {
  const [theme, setTheme] = useState(null);

  const changeTheme = () => {
    debugger;
    setTheme(theme === "1" ? "2" : "1");
  };

  useLayoutEffect(() => {
    setTimeout(() => {
      if (theme !== THEME_2) {
        setTheme(THEME_2);
      } else {
        setTheme(THEME_1);
      }
    }, 5000);
  }, []);

  return (
    <>
      <React.Suspense fallback={<></>}>
        {theme === "1" && <Theme1 />}
        {theme === "2" && <Theme2 />}
      </React.Suspense>
      <button type="checkbox" value={theme} onClick={changeTheme}>Change Theme</button>
      {children}
    </>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM