简体   繁体   English

在React中重写样式组件

[英]Override styled-components in React

I'm trying to find a way to override a styled component with styled-components like this: 我正在尝试找到一种方法来用样式化组件覆盖样式化组件,如下所示:

Let's say I have a reusable component Wrapper: 假设我有一个可重用的组件包装器:

class Wrapper extends Component {

  ...

  render() {
    const Wrap = styled.div`
      padding: 5px;
      background-color: green;
    `;
    return (
       <Wrap>
         {children}
       </Wrap>
    )
  }
}

export default Wrapper

And then I have Component B that imports Wrapper but should extend the styles like this: myNewWrap uses Wrapper 然后,我有了导入Wrapper的组件B,但应该扩展如下样式: myNewWrap使用Wrapper

import Wrapper from './Wrapper'

class B extends Component {

  ...

  render() {
    const myNewWrap = styled(Wrapper)`
      background-color: red;
    `;
    return (
       <myNewWrap>
         Some awesome text
       </myNewWrap>
    )
  }
}

Result should be that Some awesome text has padding from Wrapper but background-color from own component. 结果应该是, 一些很棒的文本从包装器中有填充,而从自己的组件中有背景色。 But what I get is only the styles from Wrapper. 但是我得到的只是包装器的样式。

Have you considered using extend from Styled-Components? 您是否考虑过使用来自样式组件的extend Styled generates new component styles with a new class whereas extend is meant to use base styling from another Styled component, but then tweak or add additional styles. Styled使用新类生成新的组件样式,而extend则意味着使用另一个Styled组件的基础样式,然后进行调整或添加其他样式。

Additionally, their docs explain when you should you use styled() (see section "When should I use styled() ?") when to use styled 此外,他们的文档解释了何时应使用styled() (请参见“何时应使用styled() ?”一节) 何时使用styled

尝试使用padding: 5px !important而不是padding: 5px;

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

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