样式化的组件:扩展样式并更改元素类型 [英] 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?
如果它们都是<div>
或<img>
,就很容易.我可以做到:
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;
`;
推荐答案
您可以从样式化组件中使用prop"as",它们将更改组件的html标签: https://www.styled-components.com/docs/api#as -polymorphic-prop
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
下面是您想要的示例:
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
You can see on : https://codesandbox.io/embed/mj3j1xp6pj?fontsize=14
这篇关于样式化的组件:扩展样式并更改元素类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文