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

React中如何通过props传递并正确渲染SVG组件?

React函数组件通过Props传入SVG渲染的实现方案

SVG的渲染方式完全取决于项目构建工具对.svg文件的解析规则,对应不同场景调整写法即可。你当前代码的问题是没有根据导入的SVG类型做对应渲染处理,直接输出{props.icon}在多数默认配置下无法正常显示图标。


场景1:SVG被解析为静态资源URL

这是Vite、Create React App等工具的默认处理逻辑:直接import xxx.svg拿到的是SVG文件的部署访问路径字符串。

  • 渲染方式:用<img>标签承接资源地址,传入src属性即可
  • 修正后的Button组件代码:
import React from "react";

export default function Button(props) {
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {/* 给图标设置统一宽高,避免尺寸错乱 */}
      <img src={props.icon} alt="" className="h-4 w-4" />
      {props.label}
    </button>
  );
}
  • 组件使用方式:
import Camera from "../icons/Camera.svg";
<Button icon={Camera} label="拍照" />

场景2:SVG被解析为React组件(推荐方案)

这种方式可以直接通过props控制SVG的填充色、描边、尺寸,灵活度远高于img方式,是目前项目开发的首选。
不同构建工具的组件导入语法略有区别:

  • Vite:导入时加?react后缀:import Camera from "../icons/Camera.svg?react";
  • Create React App:用具名导入方式:import { ReactComponent as Camera } from "../icons/Camera.svg";
  • Next.js:搭配@svgr/webpack配置后可直接作为组件导入

渲染注意:传入的props.icon是组件函数,不能直接用{props.icon}输出,必须转为JSX标签形式渲染,注意JSX要求组件名首字母大写,所以可以先把props上的icon赋值给大写开头的变量再使用。

  • 修正后的Button组件代码:
import React from "react";

export default function Button(props) {
  // 赋值给大写开头的变量,满足JSX组件渲染规则
  const Icon = props.icon;
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {/* 用fill-current让图标继承按钮文字颜色,样式统一 */}
      <Icon className="h-4 w-4 fill-current" />
      {props.label}
    </button>
  );
}
  • 组件使用方式:
// 以Vite为例,其他工具替换对应导入语法即可
import Camera from "../icons/Camera.svg?react";
<Button icon={Camera} label="拍照" />

场景3:传入内容为SVG原始字符串

如果传入的是手写的SVG标签字符串,需要用dangerouslySetInnerHTML渲染,注意仅在你完全信任SVG内容来源时使用该方式,避免XSS风险:

<span dangerouslySetInnerHTML={{ __html: props.iconString }} />

踩坑提示:如果直接写{props.icon},当传入的是React组件时,React只会把组件函数作为普通值输出,不会执行组件渲染逻辑,必须以<组件名 />的标签形式书写才能正常渲染。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:33:18