简体   繁体   中英

Styled components not overriding styles from another component

I have a component that is already built out like so:

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

and I'm trying to override the styles of the h1 and h2 and add new styles like so in another component:

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

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

However, none of that is happening. I'm assuming it's because it's nested in there? Am I able to override the styles? Or should I just build a similar component to it?

If you are styling one of your own custom components, you must make sure you use the 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: ...
  }
`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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