繁体   English   中英

React内联样式与客户端CSS冲突

[英]React Inline styles clashes with the Client CSS

我们需要在客户页面中加载我们的应用程序。 我们正在使用React构建它们。 因此,我们通过将样式定义为对象来使用React内联样式。 但是我们遇到了一个问题。 当客户端使用标签属性指定任何CSS时。 我们从未内联定义的属性会获得客户端css的tag属性中使用的属性。

下面的代码是我们用于导航栏的react inline样式。

var style = {
navigation: {
    minWidth: '50px ',
    position: 'relative ',
    marginBottom: '20px ',
    border: '1px solid transparent '
},
};
render function() {
 return(<nav style={style.navigation}> ...... </nav>);
}

在客户端,他使用样式标签属性定义导航栏。

nav{height:40px;}

在这种情况下,客户端定义的nav属性也会添加到我们的内联样式中,从而造成很多麻烦。

提出一些更好的解决方案。 在这种情况下,使用Reset类是唯一的解决方案?

您需要重置组件中受客户端CSS影响的所有CSS样式。 一种方法是使用CSS all属性

CSS all速记属性将除unicode-bidi和direction之外的所有属性重置为其初始值或继承的值。

IE或Edge不支持此解决方案的all问题。

var style = {
  navigation: {
    all: 'initial',
    minWidth: '50px ',
    position: 'relative ',
    marginBottom: '20px ',
    border: '1px solid transparent '
  },
};

render function() {
  return(<nav style={style.navigation}> ...... </nav>);
}

这是一个实际的例子-显示相同的<Nav />组件,一个使用CSS all: initial属性,另一个不使用CSS。 如前所述,这将不适用于Internet Explorer或Edge。

 class Nav extends React.Component { render() { var style = { navigationWithAll: { all: 'initial', border: '1px solid red' }, navigation: { minWidth: '50px ', position: 'relative ', marginBottom: '20px ', border: '1px solid red' } }; return ( <div> <nav style={style.navigation}>Navigation</nav> <nav style={style.navigationWithAll}>Navigation</nav> </div> ) } } ReactDOM.render( <Nav />, document.getElementById('app') ); 
 nav { height: 100px; background-color: gray; font-family: "Comic Sans MS"; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

如果可能需要支持IE或Edge,则将需要重置正在继承的特定CSS属性。 可以使用以下简单的方法完成此操作:

styles = {
  navigation: {
    height: 'initial'
  }
}

但是更健壮的解决方案(可在所有客户端站点上使用)将导入CSS组件重置。

reset = {
    margin: 'initial',
    padding: 'initial',
    height : 'auto',
    height: 'initial',
    width: 'auto',
    // any other properties you want to reset, or a full list of CSS properties to reset to initial/auto
  }
}

然后将此重置导入到您的组件样式中

import reset from 'reset'  

styles = {
  navigation: {
    ...reset,
    border: 1px solid red,
    // your custom styles
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM