【问题标题】:Extending styled components properties?扩展样式组件属性?
【发布时间】:2019-10-27 16:01:28
【问题描述】:

H1.js

export default styled.h1`
  margin: 0px;
  color: white;
`;

我想改变这个组件的颜色,我试过了

import H1 from "./H1";

const ColoredH1 = styled(H1)`
    color: "black"
`; 

但这不是改变H1的颜色吗?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    不要使用"black" 带引号,记住您在styled-component 中编写CSS,因此“黑色”不是有效颜色,尽管black 可以。 p>

    const ColoredH1 = styled(H1)`
      /* color: "black"; */  /* Invalid Color */
    
      color: black;          /* Valid Color */
      color: ${"black"}      /* Or use a valid color representation as String */
    `;
    

    【讨论】:

    • styled.h1`` color: "black" `` 出于你意想不到的原因,正如所说的 "black" 不是有效的颜色,所以它没有覆盖默认值black,尝试“黄色”并查看差异
    • 是的,我明白了。谢谢。
    【解决方案2】:

    color: black代替color: "black"

    import H1 from "./H1";
    
    const ColoredH1 = styled(H1)`
        color: black;
    `; 
    

    为了您的理解

    const Button = styled.button`
      color: red;
      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border: 2px solid red;
      border-radius: 3px;
    `;
    
    const CoralButton = styled(Button)`
      color: coral;
      border-color: coral;
    `;
    render(
      <div>
        <Button>Normal Button</Button>
        <CoralButton>Tomato Button</CoralButton>
      </div>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 2020-01-09
      • 2014-03-17
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多