You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何通过Props自定义SVG图标宽高?

如何给统一的SVG组件添加宽高Props?

要实现通过Props修改图标宽高,你需要调整类型定义、重构图标存储方式,并修改组件的Props传递逻辑,具体步骤如下:

步骤1:更新类型定义(type.ts)

先扩展组件的Props类型,添加可选的宽高属性,同时调整图标映射的类型,让每个图标支持接收宽高参数:

export interface SVGCustomIconProps {
  name: string;
  width?: number | string; // 支持数字(像素)或字符串(如"2rem")
  height?: number | string;
}

export interface SVGCustomIconMap {
  [key: string]: (props: { width?: number | string; height?: number | string }) => React.ReactNode;
}

步骤2:重构图标定义为函数式

把原本写死宽高的静态JSX改成函数,让图标可以接收宽高参数,同时保留原尺寸作为默认值:

const icons: SVGCustomIconMap = {
  InboxMenu: ({ width = 18, height = 20 }) => (
    <Svg width={width} height={height} viewBox="0 0 18 20" fill="none">
      <Path
        d="M11.25 17.5c0 .629-.262 1.3-.73 1.77-.47.468-1.141.73-1.77.73a2.5 2.5 0 01-1.77-.73 2.563 2.563 0 01-.73-1.77h5z"
        fill="#949494"
      />
      {/* 其他路径内容 */}
    </Svg>
  ),
  ProfileMenu: ({ width = 20, height = 22 }) => (
    <Svg width={width} height={height} viewBox="0 0 20 22" fill="none">
      {/* 图标路径内容 */}
    </Svg>
  ),
};

步骤3:修改SVGCustomIcon组件传递Props

调整组件逻辑,把接收的宽高参数传递给对应的图标函数:

const SVGCustomIcon = ({ name, width, height }: SVGCustomIconProps) => {
  const IconComponent = icons[name];
  return IconComponent ? IconComponent({ width, height }) : null;
};

export default SVGCustomIcon;

使用方式

现在你可以自由通过Props控制图标尺寸了:

// 使用默认尺寸
<SVGCustomIcon name="InboxMenu" />

// 自定义像素尺寸
<SVGCustomIcon name="InboxMenu" width={24} height={26} />

// 使用字符串单位(如rem、em)
<SVGCustomIcon name="ProfileMenu" width="2rem" height="2.2rem" />

内容的提问来源于stack exchange,提问作者Julia Schafer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:20:38