假设我有以下样式:
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;
`;
最佳答案
您可以使用 styled-components 中的属性“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 上看到
关于javascript - styled-components:扩展样式和改变元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55776961/