[英]Dynamic loading icon
您好有一个导入位置的脚本,它由多个 svg 文件和一个 index.ts 文件组成,用于导入和导出它们。
import * as Icons from '../../icons'
然后我有一个功能组件,它根据图标名称返回图标,但我遇到了错误。
interface props extends React.SVGProps<SVGSVGElement> {
icon: string
title?: string | undefined
}
function Icon({ icon, ...props }: props) {
const Icon = Icons[icon] <= error here
return <Icon {...props} />
}
function SidebarContent() {
return (
//some code here
<Icon className="w-5 h-5" aria-hidden="true" icon={route.icon} />
//some code here
)
}
我得到的错误是:
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)
我想知道如何在 Icon 组件中。 它如何接受图标名称 (Icon[name]) 并返回正确的图标? 或者可能还有其他方法可以做到这一点?
更多信息:如果我编写如下代码,那么它可以毫无怨言地工作。 但是,这不符合目的,因为我的意图是根据我传递的图标名称动态加载图标。
function Icon({ icon, ...props }: props) {
const Icon = Icons.ButtonsIcon
return <Icon {...props} />
}
更新:
这是我认为您正在尝试做的 CodeSandbox。
https://codesandbox.io/embed/frosty-stitch-li3wiz?fontsize=14&hidenavigation=1&theme=dark
如果您发布了一个代码框,我可以通过这种方式提供更好的帮助,但是,只要您的图标本身就是组件,而不仅仅是 SVG,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.