如何在React中将SVG图标作为组件属性传入?
实现React组件接收自定义SVG图标作为属性
1. 定义正确的TypeScript类型
在ButtonProps中,icon的类型可以用React.ElementType,它能兼容所有React组件(包括你的自定义SVG组件)。如果要严格限定为SVG组件,也可以使用更具体的React.ElementType<React.SVGProps<SVGSVGElement>>。
代码示例:
import type { ElementType } from 'react'; // 通用类型(兼容所有React组件) interface ButtonProps { icon: ElementType; } // 严格限定为SVG组件的类型 interface ButtonProps { icon: ElementType<React.SVGProps<SVGSVGElement>>; }
2. 修正组件渲染逻辑
React要求自定义组件名称必须大写开头,否则会被识别为原生HTML标签。所以要把解构的变量名改成大写开头(比如Icon),再进行渲染。
完整Button组件代码:
import type { ElementType } from 'react'; interface ButtonProps { icon: ElementType; } export const Button = ({ Icon }: ButtonProps) => { return ( <button> <Icon className="icon" /> </button> ); };
3. 自定义SVG图标组件示例
自定义SVG图标和普通React函数组件写法一致,示例如下:
// 自定义勾选图标 export const CustomCheckIcon = () => { return ( <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /> </svg> ); }; // 自定义星星图标 export const CustomStarIcon = () => { return ( <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" /> </svg> ); };
4. 使用Button组件
直接把自定义图标组件作为icon属性传入即可:
// 使用勾选图标 <Button icon={CustomCheckIcon} /> // 使用星星图标 <Button icon={CustomStarIcon} />
扩展:传递额外图标属性
如果需要给图标传递颜色、尺寸这类属性,可以在ButtonProps中新增iconProps字段,用来传递SVG相关属性:
import type { ElementType } from 'react'; interface ButtonProps { icon: ElementType<React.SVGProps<SVGSVGElement>>; iconProps?: React.SVGProps<SVGSVGElement>; } export const Button = ({ Icon, iconProps }: ButtonProps) => { return ( <button> <Icon className="icon" {...iconProps} /> </button> ); };
使用时可传入额外属性:
<Button icon={CustomStarIcon} iconProps={{ fill: '#ffd700', width: '28px' }} />
内容的提问来源于stack exchange,提问作者Ugus
相关产品推荐
相关产品推荐

