【问题标题】:Styled components not overriding styles from another component样式化的组件不会覆盖来自另一个组件的样式
【发布时间】:2018-08-01 22:55:29
【问题描述】:

我有一个已经像这样构建的组件:

const Banner = ({ image, heading, text }) => (
  <Container>
    <Background src={image}>
      <BannerContent>
        <h1>{heading}</h1>
        <h2>{text}</h2>
      </BannerContent>
    </Background>
  </Container>
);

const BannerContent = styled.div`
  h1 {
    font-size: 24px;
  }

  h2 {
    font-size: 16px;
  }
`;

我正在尝试覆盖 h1h2 的样式,并像这样在另一个组件中添加新样式:

const PageBanner = styled(Banner)`
  h1 {
    font-size: 20px;
    width: ...
  }

  h2 {
    font-size: 13px;
    width: ...
  }
`;

但是,这一切都没有发生。我假设它是因为它嵌套在那里?我可以覆盖样式吗?还是我应该只构建一个与之类似的组件?

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    如果您正在为自己的自定义组件之一设置样式,则必须确保使用className prop that styled components gives to the component

    const Banner = ({ image, heading, text, className }) => (
      <Container className={className}>
        <Background src={image}>
          <BannerContent>
            <h1>{heading}</h1>
            <h2>{text}</h2>
          </BannerContent>
        </Background>
      </Container>
    );
    
    const PageBanner = styled(Banner)`
      h1 {
        font-size: 20px;
        width: ...
      }
    
      h2 {
        font-size: 13px;
        width: ...
      }
    `;
    

    【讨论】:

    • 这是否意味着我必须在PageBanner 中传递一个类名? &lt;PageBanner className="name" 之类的东西并在 PageBanner 下设置类名的样式?
    • @Spacebear5000 不,它只是意味着样式化的组件将在后台创建一个新的类名并将其发送到包装的Banner 组件。你只需要确保你使用的是 className 提供给 Banner 组件的道具。
    • 我在这方面浪费了 如此 很多时间,我什至阅读了文档的那一部分,但并没有真正理解。不过,我才刚刚开始学习 React,所以谢谢你,@Tholle!
    猜你喜欢
    • 2021-08-02
    • 2020-07-21
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2021-11-01
    • 2018-06-27
    • 2020-10-23
    相关资源
    最近更新 更多