How to change styles while route changing in react?

…衆ロ難τιáo~ 提交于 2020-08-10 03:35:05

问题


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. 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'(i.e. HomePage), page1style.css and page2style.css will load, but I still not visit page1 and page2.


回答1:


change it like this

Page1:

 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. This way would be more modular and easy to handle



来源:https://stackoverflow.com/questions/45228589/how-to-change-styles-while-route-changing-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!