简体   繁体   English

动态加载图标

[英]Dynamic loading icon

Hi have a script that import location, which consists of multiple svg file and a index.ts file to import and export them.您好有一个导入位置的脚本,它由多个 svg 文件和一个 index.ts 文件组成,用于导入和导出它们。

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

I then have a functional component that returns the icon based on the icon name, which I am getting error.然后我有一个功能组件,它根据图标名称返回图标,但我遇到了错误。

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
  )
}

The error I am getting is this:我得到的错误是:

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)

I would like to know how in the Icon component.我想知道如何在 Icon 组件中。 How can it accept icon name (Icon[name]) and return the correct icon?它如何接受图标名称 (Icon[name]) 并返回正确的图标? or probably there is other way to do this?或者可能还有其他方法可以做到这一点?

More info: If I write the code like the following then it works without complaining.更多信息:如果我编写如下代码,那么它可以毫无怨言地工作。 However that doesn't fit the purpose because my intention is to dynamically load the icon based on the icon name i've passed.但是,这不符合目的,因为我的意图是根据我传递的图标名称动态加载图标。

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

Updated:更新:

Here's a CodeSandbox of what I believe you're trying to do.这是我认为您正在尝试做的 CodeSandbox。

https://codesandbox.io/embed/frosty-stitch-li3wiz?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/embed/frosty-stitch-li3wiz?fontsize=14&hidenavigation=1&theme=dark

If you posted a codesandbox I could assist better that way, however, as long you Icons are components themselves, not just SVGs, it should work.如果您发布了一个代码框,我可以通过这种方式提供更好的帮助,但是,只要您的图标本身就是组件,而不仅仅是 SVG,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM