如何防止外部CSS添加和覆盖ReactJS组件样式 [英] How to prevent outside CSS from adding and overriding ReactJS component styles

查看:51
本文介绍了如何防止外部CSS添加和覆盖ReactJS组件样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的ReactJS组件,我想以某种方式设置样式并将其作为插件提供给许多不同的网站.但是,当网站使用全局样式(Twitter引导程序或其他CSS框架)时,它会添加并覆盖我的组件的样式.例如:

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:

global.css:

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

component.js:

component.js:

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

结果:

上面,我没有在组件样式中使用"font-weight:bold",但是结果是我的组件正在使用它.

我希望能够封装我的自定义组件的样式,使它们在所有网站上看起来都一样.

推荐答案

在我看来,最好的方法是为您的组件定义某种重置类,并放入一组CSS重置,您可以在那里找到它们(例如 http://meyerweb.com/eric/tools/css/reset/)

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/)

sass 文件中的定义如下所示:

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
}

要避免在不想使用 sass 时写很多东西,只需使用通用选择器 * :

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

这篇关于如何防止外部CSS添加和覆盖ReactJS组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆