样式化的组件不会覆盖其他组件的样式

时间:2018-08-01 14:53:16

标签: javascript reactjs styled-components

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

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: ...
  }
`;

但是,这些都没有发生。我以为是因为它嵌套在里面?我可以覆盖样式吗?还是我应该为其构建类似的组件?

1 个答案:

答案 0 :(得分:3)

如果要样式化自己的自定义组件之一,则必须确保使用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: ...
  }
`;
相关问题