styled-components: extend styles and change element type

你说的曾经没有我的故事 提交于 2020-12-05 06:54:26

问题


Imagine I have the following styles:

color: black;
border: 1px solid white;

and I want to apply them both to two elements of different types:

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

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

How can I make both elements extend those styles?


It's easy enough if they were both <div> or <img>. I could do:

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

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

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

回答1:


You can use prop "as" from styled-components who will change html tag of your component: https://www.styled-components.com/docs/api#as-polymorphic-prop

Below an example of what you want:

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

You can see on : https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14



来源:https://stackoverflow.com/questions/55776961/styled-components-extend-styles-and-change-element-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!