Hi有一个导入位置的脚本,该脚本由多个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)我想知道如何在图标组件。它如何接受图标名(图标)并返回正确的图标?或者也许还有别的办法可以做到?
更多信息:如果我像下面这样编写代码,那么它可以正常工作,不会有任何抱怨。然而,这并不符合我的目的,因为我的意图是根据我传递的图标名动态加载图标。
function Icon({ icon, ...props }: props) {
const Icon = Icons.ButtonsIcon
return <Icon {...props} />
}Update:我就是这样修复类型错误的:
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} />
}发布于 2022-08-23 06:05:11
更新:
下面是我认为你想做的事情的CodeSandbox。
Icon.js
import react from "react";
import * as Icons from "./icons";
export default function Icon({ icon, ...props }) {
const NewIcon = Icons[icon];
return <NewIcon {...props} />;
}图标/index.js
import { ReactComponent as ButtonIcon } from "./button.svg";
import { ReactComponent as BellIcon } from "./bell.svg";
export { BellIcon, ButtonIcon };App.js
import Icon from "./Icon";
export default function App() {
return (
<div className="App">
<Icon icon="BellIcon"></Icon>
<Icon icon="ButtonIcon"></Icon>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}https://codesandbox.io/embed/frosty-stitch-li3wiz?fontsize=14&hidenavigation=1&theme=dark
如果您发布了一个代码框,我可以通过这种方式提供更好的帮助,但是,只要您的图标本身是组件,而不仅仅是SVG,它就应该能工作。
https://stackoverflow.com/questions/73453665
复制相似问题