javascript - 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;
`;
解决方案
您可以使用 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;
`;
推荐阅读
- docker - 如何在谷歌云构建器中缓存多阶段 docker 构建
- java - Java - 类名以数字开头
- r - 如何利用和操作“RasterBrick”中的土地覆盖图以进行 R 中的面积加权统计?
- python - Pandas 在其相似列上合并 2 个数据框(即索引)
- python - 如何训练 Pytorch 网络
- agent - 在 anylogic 中使用投递块投递特定的自定义代理
- c# - c# 在字节数组上应用 64 位 XOR
- mongodb - MongoDB 聚合 - 从给定数组创建新数组
- javascript - Angular 5 - 如何在某些路由上加载某些 css 样式(引导 css 仅适用于管理路由)
- web-applications - Context.Request.GetHttpContext() 在 SignalR 服务器中为浏览器功能返回 null