【问题标题】:Unable to override Styled Component in React无法在 React 中覆盖样式化组件
【发布时间】:2022-06-18 18:38:04
【问题描述】:

我在一个文件中有一个BaseComponent,它由几个其他组件组成,我正在导出该组件。 BaseComponent 的最高级别有一个负责边距的包装器。当我导出它并尝试用

覆盖一些样式时
 //other file

const BaseComponentWrapper = styled.div`
  margin: 10px
`

const export BaseComponent = () => {
  return (
      <BaseComponentWrapper>
          Some other stuff in the middle
      </ BaseComponentWrapper >
}
import { BaseComponent } from otherfile

const ModifiedBaseComponent = styled(BaseComponent)`
  margin: 0 px;
`

我的ModifiedBaseComponent 的边距不会更改为0px

我能够更改边距的唯一方法是从浏览器中获取样式组件生成的类并将其插入到包装器 css 下,例如

const BaseComponentWrapper {
  .etbykw {
     margin: 0px;
  }
}

据我所知,至少下面的这段代码应该可以工作,但它也不能

const BaseComponentWrapper {
  > ${ModifiedBaseComponent} {
     margin: 0px;
  }
}

从我在其他问题上看到的情况来看,关于 className 道具的某些内容可能有用,但我无法理解这一点。我知道这是某种特殊性问题,但我真的很难完全理解这一点,而且有效的代码对于外界来说不是很易读。

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    要设置通用组件的样式,您必须传递 className 属性。

    在下面的示例中,BaseComponent 接受一个类名并将其传递给 BaseComponentWrapper。

    现在您可以设置 BaseComponent 的样式了。

    文档:https://styled-components.com/docs/advanced#styling-normal-react-components

    const BaseComponentWrapper = styled.div`
      margin: 10px;
    `;
    
    export const BaseComponent = ({ className, children }) => {
      return (
        <BaseComponentWrapper className={className}>
          {children}
        </BaseComponentWrapper>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 2021-11-01
      • 2020-10-16
      • 1970-01-01
      • 2017-04-02
      • 2020-07-21
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多