【问题标题】:styled-components: extend styles and change element typestyled-components:扩展样式并更改元素类型
【发布时间】:2019-09-10 14:48:29
【问题描述】:

假设我有以下样式:

color: black;
border: 1px solid white;

我想将它们都应用于不同类型的两个元素:

const SomeImg = styled.img`
  margin: 2em;
`;

const SomeDiv = styled.div`
  margin: 3em;
`;

如何让这两个元素都扩展这些样式?


如果他们都是<div><img>,那就很容易了。我可以这样做:

const ExtendMe = styled.div`
  color: black;
  border: 1px solid white;
`;

const SomeDiv = styled(ExtendMe)`
  margin: 2em;
`;

const OtherDiv = styled(ExtendMe)`
  margin: 3em;
`;

【问题讨论】:

    标签: javascript html css reactjs styled-components


    【解决方案1】:

    您可以使用 styled-components 中的 prop "as" 来更改组件的 html 标签: https://www.styled-components.com/docs/api#as-polymorphic-prop

    下面是您想要的示例:

    const ExtendMe = styled.div`
      color: black;
      border: 1px solid white;
    `;
    
    const SomeImg = styled(ExtendMe).attrs({
      as: "img"
    })`
      margin: 2em;
    `;
    
    
    const SomeDiv = styled(ExtendMe)`
      margin: 3em;
    `;
    
    

    你可以看到:https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2019-12-21
      • 2021-06-02
      • 1970-01-01
      • 2021-09-22
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多