css - 路由的不同 css 样式表

标签 css reactjs create-react-app react-router-dom

我对 React 和 React-router-dom 很陌生。问题是,我正在尝试为我的应用程序中的不同路线获取不同的布局。但是,不同路由的所有 css 文件只是在一个巨大的冲突片段中导入。

应用看起来像这样:

<Router>
  < >
    <Navigation />
    <UpButton />
    <Switch>
      <Route path="/" exact component={Home} />
      <Route path="/research" component={Research} />
      <Route path="/publications" component={Publications} />
      <Route path="/student" component={Student} />
      <Route path="/about" component={About} />
    </Switch>
  </>
</Router>

我渲染的每个组件看起来像这样:

import React from 'react';
import './home.scss';

// Utility
import Utility from 'components/utility/Utility';

class Home extends React.Component {
  render() {
    return (
      < >
        <Utility />
      </>
    );
  }
}

export default Home;

有没有办法只导入具有特定路由的特定 css 文件?比如“/”路由的 home.css,“/about”路由的 about.css?

这可能是我的简单误解,但我现在真的找不到任何解决办法。

最佳答案

我建议使用以下文件结构和模式:

- components
  - Main.js
  - Utility
    - index.js
    - styles.scss
- pages
    - HomePage
      - index.js
      - styles.scss

然后在组件样式表中指定与组件相关的样式,并在页面样式表中指定与页面相关的样式。并将页面用于路由,而不是组件。 最后,将每个组件包装到一个特定的类选择器中,并将所属的 sass 文件添加到该选择器中(如 .home-page)。 出于这个原因,请使用 sass 而不是 css,因为您可以将样式定义嵌入彼此并将顶部的用作“命名空间”。所以样式不会相互影响。

// Main.js
  import HomePage from '../pages/HomePage';

  <Switch>
    <Route path="/" exact component={HomePage} />
    <Route path="/research" component={ResearchPage} />


// HomePage/index.js

  import Utility from './components/Utility';
  import './styles.scss';
  ...
  render(){
    <div className="home-page">
      <Utility />
    </div>
  }

// HomePage/styles.scss    
  .home-page {
    ...
  }

// Utility/index.js

  import './styles.scss';
  ...

  render(){
    return (
      <div className="utility-comp">
      ...
      </div>
  }


// Utility/styles.scss
  .utility-comp {
    ...
  }

关于css - 路由的不同 css 样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57323035/

相关文章:

html - 悬停时更改字体大小移动其他div

reactjs - 如何在nextjs中导航而不会丢失标题组件的状态

javascript - npm 测试没问题,但它也会引发 Uncaught Error AskBackend ReferenceError : localStorage is not defined

html - 需要帮助拆分侧边栏具有 3 个不同的列表高度

reactjs - 如何使用 CRA 将类型声明添加到 react-typescript 项目

css - 在 create-react-app 中生成 RTL CSS 文件并根据状态变化在它们之间切换

javascript - 使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如::before 和::after

html - 可以使用 CSS 反转无序列表中元素的分层吗?

html - Chrome 错误 : skewed element looks pixelated

javascript - react 绑定(bind)功能