You need to enable JavaScript to run this app. 如何将相同的styled-components样式应用到多个已导入的SVG组件?
优惠活动
大模型
产品
解决方案
定价
更多

如何将相同的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 14:36:03