【问题标题】:Overriding a styled-component with new styled-component?用新的样式组件覆盖样式组件?
【发布时间】:2019-10-03 08:17:08
【问题描述】:

我有三个样式组件 StyledBannerStyledTitleWarningBanner

我希望通过WarningBanner 覆盖StyledBanner 颜色,但没有成功,返回组件总是回退到 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>)

【问题讨论】:

  • 你有没有尝试过类似css selector { property: value!important }
  • 你应该使用color而不是colors

标签: css styled-components


【解决方案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'),
);

【讨论】:

  • 谢谢,另外我的样式末尾缺少一个分号。
猜你喜欢
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2017-04-02
  • 2020-10-16
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
相关资源
最近更新 更多