用新的样式化组件覆盖样式化组件?

时间:2019-10-02 21:39:13

标签: css styled-components

我有三个样式组成部分:StyledBannerStyledTitleWarningBanner

我正在尝试通过StyledBanner覆盖WarningBanner的颜色,但是无法正常工作,并且返回Component总是回到div的颜色。

如何重新设置样式化组件的样式?

const StyledBanner = styled.div`
  background-color: ${theme.colors.blue_2};
  padding: 15px;
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  width: 100%;
`;

const StyledTitle = styled(PG)`
  font-size: 1.125rem;
  font-weight: bold;
  padding: 0px 0px 15px 0px;
  colors: ${theme.colors.blue_2}

`

const WarningBanner = styled(StyledBanner)`
  background-color: ${theme.colors.banner_yellow}

  ${StyledTitle}{
    colors: ${theme.colors.textColor}
`
...

return (<WarningBanner> //still showing theme.colors.blue_2
      {title ? <StyledTitle> //still showing theme.colors.blue_2
        {title}
      </StyledTitle> : null}
      </WarningBanner>)

1 个答案:

答案 0 :(得分:1)

您在已发布的代码中有一个较小的错字(您要设置的CSS属性为color,而不是复数)。否则,您的方法完全正确。

工作示例:https://codepen.io/mattlubner/pen/XWrvQLP

const theme = {
  colors: {
    red: '#f00',
    greed: '#0f0',
    blue: '#00f',
    yellow: '#ff0',
  },
};

const StyledBanner = window.styled.div`
  background-color: ${theme.colors.blue};
  padding: 15px;
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  width: 100%;
`;

const StyledTitle = window.styled.h1`
  font-size: 1.125rem;
  font-weight: bold;
  padding: 0px 0px 15px 0px;
  color: ${theme.colors.blue};
`;

const WarningBanner = window.styled(StyledBanner)`
  background-color: ${theme.colors.yellow};
  ${StyledTitle} {
    color: ${theme.colors.green};
`;

ReactDOM.render(
  <WarningBanner>
    <StyledTitle>Example Title</StyledTitle>
  </WarningBanner>,
  document.getElementById('root'),
);