【问题标题】:Load a component's CSS only if it is rendered仅在渲染组件时才加载组件的 CSS
【发布时间】:2020-07-16 00:11:39
【问题描述】:

在一个项目中,我有不同的组件和不同的 css 导入,在应用程序中我使用 react-router 来定义路径。当我访问 /anycomponent 时,我将它们的导入放在了头部,但其他组件的所有 css 也都放在了那里。有没有办法只在渲染时导入组件的css?

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import component1 from './pages/component1';
import component2 from './pages/component2';

export default function Routes() {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/" exact component={component1} />
                <Route path="/component2" component={component2} />
            </Switch>
        </BrowserRouter>
    );
}

【问题讨论】:

  • 为什么要这样做?当然最好是尽可能多地聚合 CSS,这样当组件渲染时,您就不必同时加载 CSS 文件?
  • 我的头上已经有 10 个样式标签,我什至不到 5%,我想避免这种不必要的导入量。它也会提高性能。
  • 你是如何设计你的组件的?您是手动创建 CSS 文件还是使用某种形式的 CSS-in-JS(如 Emotion)?
  • 我正在手动创建 css 文件,每个组件一个。
  • 您应该真正考虑使用 CSS-in-JS,例如 Emotion、Styled Components 或类似的东西。如果您正在创建单独的文件,那么您的存储库就会膨胀并使代码更难维护。 Emotion 非常适合创建特定于组件的 CSS,Emotion 在编译时为您处理所有 CSS 捆绑。

标签: css reactjs react-router


【解决方案1】:

尝试延迟加载组件:

const Component1 = lazy(() => import('./pages/component1'));
const Component2 = lazy(() => import('./pages/component2'));

<BrowserRouter>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Component1 }/>
        <Route path="/component2" component={Component2 }/>
      </Switch>
    </Suspense>
</BrowserRouter>

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2022-01-06
    • 1970-01-01
    • 2020-07-10
    • 2021-07-15
    • 2021-05-26
    • 2013-01-20
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多