css - create-react-app 中的条件 CSS

标签 css reactjs create-react-app

我有默认的 css 文件和单独的 css 文件,只有在满足某些条件时才应应用(以默认设置)。

我正在使用带有默认 import 'file.css' 语法的 create-react-app。

决定是否动态加载特定 css 文件的最佳方式是什么?

最佳答案

require 方法仅在开发中有效(因为所有 CSS 都在构建时捆绑在一起),而 import 方法根本不起作用(使用 CRA 3.3 版) .

在我们的例子中,我们有多个主题,不能捆绑 - 所以我们使用 React.lazyReact.Suspense 解决了这个问题。

我们有 ThemeSelector,它有条件地加载正确的 css。

import React from 'react';

/**
 * The theme components only imports it's theme CSS-file. These components are lazy
 * loaded, to enable "code splitting" (in order to avoid the themes being bundled together)
 */
const Theme1 = React.lazy(() => import('./Theme1'));
const Theme2 = React.lazy(() => import('./Theme2'));

const ThemeSelector: React.FC = ({ children }) => (
  <>
    {/* Conditionally render theme, based on the current client context */}
    <React.Suspense fallback={() => null}>
      {shouldRenderTheme1 && <Theme1 />}
      {shouldRenderTheme2 && <Theme2 />}
    </React.Suspense>
    {/* Render children immediately! */}
    {children}
  </>
);

export default ThemeSelector;

Theme 组件的唯一工作是导入正确的 css 文件:

import * as React from 'react';

// 👇 Only important line - as this component should be lazy-loaded,
//    to enable code - splitting for this CSS.
import 'theme1.css';

const Theme1: React.FC = () => <></>;

export default Theme1;

ThemeSelector 应该将 App 组件包装在 src/index.tsx 中:

import React from 'react';
import ReactDOM from 'react-dom';
import ThemeSelector from 'themes/ThemeSelector';

ReactDOM.render(
  <ThemeSelector>
    <App />
  </ThemeSelector>,
  document.getElementById('root')
);

据我所知,这迫使每个 Theme 被拆分成单独的包(实际上也拆分了 CSS)。


如评论中所述,此解决方案并未提供切换主题运行时的简单方法。该解决方案侧重于将主题拆分为单独的包。

如果您已经将主题拆分为单独的 CSS 文件,并且想要交换主题运行时,您可能需要查看使用 ReactHelmet ( illustrated by @Alexander Ladonin's answer below ) 的解决方案

关于css - create-react-app 中的条件 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46835825/

相关文章:

HTML anchor 标记

reactjs - 在 React Native 中计算两个 lat+lng 坐标之间的距离?

jquery - 使用选项卡内容菜单时,砌体显示在页面底部

html - 调整 div 大小以适应子跨度

css - 不执行 CSS3 过渡

node.js - 从 react 到 Node 发送数据时出现问题

reactjs - 如何从 React 功能组件声明 TypeScript 静态方法

reactjs - 如何将 Create React App Production Error Boundary 映射到源代码

reactjs - 创建 react 应用程序 RangeError : Maximum call stack size exceededat Object. mkdirSync

javascript - 与 create-react-app 项目 react 的视频标签