【问题标题】:How to change styles while route changing in react?如何在路线更改时更改样式?
【发布时间】:2017-12-26 23:16:52
【问题描述】:

当 route(react-route) 发生变化时,如何加载或删除与新页面相关的样式?我真的不知道谁在负责这个功能,react 或 webpack 或 react-router。但是现在首页加载完,项目里的所有样式都加载了,怎么办?

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 {}

像代码一样,当我访问“http://localhost:8080”(即主页)时,page1style.csspage2style.css 将加载,但我仍然没有访问 page1page2

【问题讨论】:

  • 您可以发布一些您可能已经拥有的代码吗?另外,您是否使用任何主题,例如 material-ui 等
  • @XPLOT1ON 我用过antd design,但我觉得没关系。 react项目是不是有问题——加载主页时,所有样式都会加载?
  • 通过使用 webpack 你可以在需要的时候加载组件,这里是链接:blog.lavrton.com/…
  • 也许这就是您要找的东西?组件样式facebook.github.io/react/docs/dom-elements.html#style 请注意,html background-image 已在 react 中替换为 backgroundImage,没有破折号 (-)
  • 但请先分享您的代码。谢谢

标签: javascript reactjs webpack react-router


【解决方案1】:

改成这样

第1页:

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

您的代码所做的是作为通用 css 加载,这就是它加载所有 css 的原因。这种方式将更加模块化且易于处理

【讨论】:

  • 你使用 webpack 作为你的打包工具吗?
  • 是的,我有,我试过css-loader moduler,但是没用。
  • 您是否将someClass 替换为您在css 中指定的名称?
猜你喜欢
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
相关资源
最近更新 更多