如何在反应中更改路线时更改样式? [英] How to change styles while route changing in react?
问题描述
当路由(react-route)改变时,如何加载或删除与新页面相关的样式?我真的不知道谁负责这个功能,react 或 webpack 或 react-router.但是现在,当首页加载时,项目中的所有样式都会加载,我该怎么办?
路线:<路由器历史={hashHistory}><IndexRoute 组件={HomePage}/><Route path="/page1" component={Page1}/><Route path="/page2" component={Page2}/></路由器>第1页:导入'./page1style.css';导出默认类 Page1 扩展 React.Component {}第2页:导入'./page2style.css';导出默认类 Page2 扩展 React.Component {}
喜欢代码,当我访问'http://localhost:8080'(即主页)时,page1style.css
和 page2style.css
将加载,但我仍然无法访问 page1
和 page2
.
改成这样
第 1 页:
从 './page1style.css' 导入样式;导出默认类 Page1 扩展 React.Component {使成为 () {return }}您的代码所做的是作为通用 css 加载,这就是它加载所有内容的原因.这种方式会更加模块化且易于处理
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
.
解决方案 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
这篇关于如何在反应中更改路线时更改样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文