首页 > 解决方案 > styled-components:扩展样式并更改元素类型

问题描述

想象一下,我有以下样式:

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

标签: javascripthtmlcssreactjsstyled-components

解决方案


您可以使用 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


推荐阅读