简体   繁体   English

使用 React 片段将内联 CSS 添加到 JS class

[英]Adding inline CSS to JS class with React Fragment

I was following this article https://prawira.medium.com/react-conditional-import-conditional-css-import-110cc58e0da6 to conditionally lazy-load CSS stylings in my React app.我正在关注这篇文章https://prawira.medium.com/react-conditional-import-conditional-css-import-110cc58e0da6在我的 React 应用程序中有条件地延迟加载 CSS 样式。 The method described involves creating a dummy JS class, eg.所描述的方法包括创建一个虚拟 JS class,例如。

import React from 'react';
import './my-styles.css';

const Theme = () => (<React.Fragment></React.Fragment>);

export default Theme;

So that it can be used like this:所以它可以像这样使用:

const styles = React.lazy(() => import("./theme"))
...
return (
<>
   <Suspense fallback={<></>}>
      {styles}
   </Suspense>
   <MyApp />
</>
);

I will need to be able to lazy load many CSS stylesheets, and I don't want to create the same JS wrapper over and over again for each one.我需要能够延迟加载许多 CSS 样式表,并且我不想为每个样式表一遍又一遍地创建相同的 JS 包装器。 Is there a way to combine the wrapper with inline CSS, or perhaps make one wrapper for all of the styles (such that the lazy-loading process still only loads the specific one I want?)有没有办法将包装器与内联 CSS 结合起来,或者可能为所有 styles 制作一个包装器(这样延迟加载过程仍然只加载我想要的特定一个?)

You should create a theme that will decide what styles have to be loaded as in the article you are refferring to:您应该创建一个主题,该主题将决定必须加载 styles 的内容,如您所引用的文章中所述:

const ThemeSelector = ({ children }) => {
  const CHOSEN_THEME = localStorage.getItem('TYPE_OF_THEME') || TYPE_OF_THEME.DEFAULT;
  return (
    <>
      <React.Suspense fallback={<></>}>
        {(CHOSEN_THEME === TYPE_OF_THEME.LIGHT_MODE) && <LightTheme />}
        {(CHOSEN_THEME === TYPE_OF_THEME.DARK_MODE) && <DarkTheme />}
      </React.Suspense>
      {children}
    </>
  )
}

In the expample you show there is no condition, by the way.顺便说一句,在示例中,您表明没有条件。 It always loads './my-styles.css'它总是加载'./my-styles.css'

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

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