【发布时间】: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