样式化组件:扩展样式和更改元素类型



想象一下我有以下样式:

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

您可以使用样式化组件中的 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

最新更新