Overlapping CSS in React, Webpack application

谁都会走 提交于 2021-02-07 08:48:05

问题


I have created an application using webpack and reactjs. So far I have created 2 pages. I have defined CSS styling for both the pages. But when I load page 2 after loading page 1, the styles from page 1 are interfering with those of page 2.

For example

Page 1

require('style1.css');
var Page1 = React.createClass({
render: function(){
  return(
<div> <h1>This is Page1</h1> <span> hello from page1</span></div>
 )
}
});

module.exports = Page1;

style1.css

span {
   color : red
}

Page 2

require('style2.css');

var Page2 = React.createClass({
render: function(){
  return(
<div> <h1>This is Page2</h1> <span> hello from page2</span></div>
 )
}
});

module.exports = Page2;

style2.css

h1 {
   color : blue
}

When page2 is loaded after page1, the color of span was red, which was loaded from page1's style. Is there any way to avoid such kind of interferences or am I doing something wrong here?


回答1:


You can have local stylesheets for each React component.

So the style sheet itself will have something like this:

:local(.styles) {

  .your-style{...}
}

You can store it in the same folder as your component code. You import the style like so:

/* component styles */
import { styles } from './styles.scss'

In the render function of your component you will have this:

return (
  <div className={styles}>
  ...
  </div>
)

Everything within that <div> will have the stylesheet applied.

Loader configuration for your Webpack:

loaders: [{
  test: /\.scss$/,
  loader: 'style!css?localIdentName=[path][name]--[local]!postcss-loader!sass',
}]

You can look at this awesome boilerplate app, that implements all of this very nicely.




回答2:


Webpack is not going to fix the inherent problems with style sheets. If you want component level styling the simplest solution is to go with inline styles. You might also look at Radium. https://github.com/FormidableLabs/radium



来源:https://stackoverflow.com/questions/35021073/overlapping-css-in-react-webpack-application

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