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

React动态加载SVG图标遇TypeScript类型错误的解决咨询

动态加载SVG图标组件的TypeScript类型问题解决

问题背景

我有一个图标目录,包含多个SVG文件及用于统一导入导出的index.ts,通过以下方式导入所有图标:

import * as Icons from '../../icons'

我编写了一个Icon组件,希望通过传入的图标名称字符串动态渲染对应SVG,但出现类型错误:

interface props extends React.SVGProps<SVGSVGElement> {
  icon: string
  title?: string | undefined
}

function Icon({ icon, ...props }: props) {
  const Icon = Icons[icon] // 此处报错
  return <Icon {...props} />
}

function SidebarContent() {
  return (
    // 部分代码省略
    <Icon className="w-5 h-5" aria-hidden="true" icon={route.icon} />
    // 部分代码省略
  )
}

报错信息

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("d:/Code/JS/meal-order/frontend/src/icons/index")'.
  No index signature with a parameter of type 'string' was found on type 'typeof import("d:/Code/JS/meal-order/frontend/src/icons/index")'.ts(7053)

补充说明

如果直接指定具体图标名称(如下代码),组件可以正常运行,但无法满足动态加载图标的需求:

function Icon({ icon, ...props }: props) {
  const Icon = Icons.ButtonsIcon
  return <Icon {...props} />
}

修复方案

我通过以下方式解决了类型错误:

import React from "react";
import * as Icons from "../../icons";

type IIcon = React.FunctionComponent<React.SVGProps<SVGSVGElement> & {
  title?: string | undefined;
}>

export default function Icon({ icon = 'MenuIcon', ...props }) {
  const myObj: { [index: string]: IIcon } = Icons
  const NewIcon = myObj[icon]
  return <NewIcon {...props} />
}

方案说明

  1. 定义IIcon类型,统一所有SVG图标组件的类型,确保它们都符合React.SVGProps<SVGSVGElement>加上可选title属性的函数组件类型;
  2. 将导入的Icons对象断言为带有字符串索引的对象类型,让TypeScript允许使用字符串类型的icon参数去索引图标集合,消除类型报错。

内容的提问来源于stack exchange,提问作者Chee Herng Huan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:36:54