简体   繁体   English

在更改路线时如何更改样式?

[英]How to change styles while route changing in react?

When route(react-route) changing, how can I load or remove the styles relevant to the new page? 更改路线(反应路线)时,如何加载或删除与新页面相关的样式? I really don't know who is in charge of this function , react or webpack or react-router. 我真的不知道谁负责这个功能,react或webpack或react-router。 But now, when the home page loaded, all of the styles in project will load, how could I do? 但是现在,当加载主页时,将加载项目中的所有样式,我该怎么办?

Routes: 

<Router history={hashHistory}>
 <IndexRoute component={HomePage}/>
 <Route path="/page1" component={Page1}/>
 <Route path="/page2" component={Page2}/>
</Router>

Page1: 

 import './page1style.css';
 export default class Page1 extends React.Component {}

Page2: 
  import './page2style.css';
  export default class Page2 extends React.Component {}

Like the code, when I visit ' http://localhost:8080 '(ie HomePage), page1style.css and page2style.css will load, but I still not visit page1 and page2 . 像代码一样,当我访问“ http:// localhost:8080 ”(即HomePage)时,将加载page1style.csspage2style.css ,但是我仍然不会访问page1page2

change it like this 像这样改变它

Page1: 第1页:

 import style from './page1style.css';
 export default class Page1 extends React.Component {
   render () {
     return <div className={style.someClass} />
   }
 }

what your code does is to load as general css and that's why it load all of it. 您的代码要做的是将其加载为通用CSS,这就是为什么它全部加载的原因。 This way would be more modular and easy to handle 这种方式将更加模块化并且易于处理

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

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