覆盖样式组件中子样式的最佳方法

Best way to override child styles in styled-components

我有一个组件,我想覆盖它的样式。我使用 styled-components 来构建它们。

我的疑问是,如何覆盖子组件的样式。

我想知道更好的方法。

例子

 const Child = styles.div'
      font-size: '10px'
    '
    const Wrapper = styles.div'
      color: red
    '
const DummyComponent = () => (
  <Wrapper>
    <Child>Hello</Child>
  </Wrapper>
)

我想更改子项的填充或边距或任何其他 属性。

更好的方法是什么。 使用内联样式或类名。或者在 styled-component 中有没有更好的方法来做到这一点。

使用内联样式

const DummyComponent = ({childStyles}) => (
  <Wrapper>
    <Child style={{...childStyles}}>Hello</Child>
  </Wrapper>
)

使用类名

const DummyComponent = ({childClass}) => (
   <Wrapper>
       <Child className={childClass}>Hello</Child>
    </Wrapper>
)

CSS !important 规则将覆盖具有更高优先级的标签。例如,如果您使用以下代码 background-color: green !important; 将 class 应用于子元素,这将覆盖可能应用于子元素的其他 background-color 规则。这是覆盖样式的最佳方式。

我建议使用类名来覆盖行为。你只需要你的规则更强大。特克斯:

const DummyComponent = ({childClass}) => (
   <Wrapper className="div--wrapper">
       <Child className="div--child">Hello</Child>
    </Wrapper>
)
// css
.div--wrapper .div--child{
  // override css go here
}