How to prevent outside CSS from adding and overriding ReactJS component styles

隐身守侯 提交于 2020-01-25 05:58:37

问题


I have a custom ReactJS component that I want to style in a certain way and provide as a plugin to many different web sites. But when web sites use global styles (Twitter bootstrap or another css framework) it adds and overrides styles of my component. For example:

global.css:

    label { 
        color: red;
        font-weight: bold;
     }

component.js:

class HelloMessage extends React.Component {
  render() {
      let style = {
          color: "green"
      };
    return (<label style={style}>Hello</label>);
  }
}

result:

Above I didn't use "font-weight: bold" in my component's style but in result my component is using it.

I'd like to be able to encapsulate my custom components's styles in a way that makes them look the same across all the web sites.


回答1:


The best approach in my view is to define some kind of reset class for your component and put in a set of css resets you can find out there (e.g. http://meyerweb.com/eric/tools/css/reset/)

The definition in a sass file could look like this:

.your-component-reset {
    div, span, object, iframe {
        margin: 0;
        padding: 0;
        border: 0;
        font-weight: normal;
        font-size: 100%;
        font: inherit;
        vertical-align: baseline;
    }
    // add some more reset styles
}

To avoid writing a lot when you don't want to use sass just use the universal selector *:

.your-component-reset * {
     margin: 0;
     padding: 0;
     font-weight: normal;
     // other reset styles ...
}


来源:https://stackoverflow.com/questions/37409233/how-to-prevent-outside-css-from-adding-and-overriding-reactjs-component-styles

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