Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

javascript - styled-components: extend styles and change element type

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;
`;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...