如何将相同的styled-components样式应用到多个已导入的SVG组件?
解决方案
共有两种常用的简洁实现方式,你可以根据实际场景选择:
方案1:封装样式工厂函数
适合所有SVG仅需要套用这套公共样式、不需要额外新增自定义样式的场景,调用最简洁:
// 提前封装公共的样式生成函数 const createStyledSvg = (SvgComponent) => styled(SvgComponent)` & path { fill: white; } &:hover path { fill: gray; } `; // 使用时仅需传入对应的导入SVG组件即可 const UpsetEmoticonStyled = createStyledSvg(UpsetEmoticon); const HappyEmoticonStyled = createStyledSvg(HappyEmoticon); const CustomIconStyled = createStyledSvg(CustomIcon);
方案2:抽离公共样式片段
使用styled-components自带的css辅助函数抽离公共样式,适合需要在公共样式基础上额外添加组件独有样式的场景,灵活性更高:
import { css } from 'styled-components'; // 抽离公共样式片段 const svgCommonStyles = css` & path { fill: white; } &:hover path { fill: gray; } `; // 使用时直接引入样式片段即可,还可叠加自定义样式 const UpsetEmoticonStyled = styled(UpsetEmoticon)` ${svgCommonStyles} `; const HappyEmoticonStyled = styled(HappyEmoticon)` ${svgCommonStyles} /* 额外添加独有样式 */ width: 20px; height: 20px; margin-right: 8px; `;
内容的提问来源于stack exchange,提问作者Mel
相关产品推荐
相关产品推荐

