How to prevent outside CSS from adding and overriding ReactJS component styles(如何防止外部 CSS 添加和覆盖 ReactJS 组件样式)
问题描述
我有一个自定义的 ReactJS 组件,我想以某种方式对其进行样式设置,并作为插件提供给许多不同的网站.但是当网站使用全局样式(Twitter bootstrap 或其他 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 组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止外部 CSS 添加和覆盖 ReactJS 组件样式
				
        
 
            
        - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - Fetch API 如何获取响应体? 2022-01-01
 - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - addEventListener 在 IE 11 中不起作用 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - 400或500级别的HTTP响应 2022-01-01
 - Flexslider 箭头未正确显示 2022-01-01
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - 失败的 Canvas 360 jquery 插件 2022-01-01
 
						
						
						
						
						