我有一个React组件,其中我将svgs作为ReactComponent
导入,在该组件中,我将svgsMap到key
字符串,该字符串将返回正确的svg。
一切工作的问题,我有一个问题, typescript 。导入React,{ SVGProps,FC }从“React”;
import { ReactComponent as FacebookLogo } from "../../images/icon-facebook.svg";
import { ReactComponent as TwitterLogo } from "../../images/icon-twitter.svg";
import { ReactComponent as InstagramLogo } from "../../images/icon-instagram.svg";
import { ReactComponent as YoutubeLogo } from "../../images/icon-youtube.svg";
import { ReactComponent as ArrowUp } from "../../images/icon-up.svg";
import { ReactComponent as ArrowDown } from "../../images/icon-down.svg";
type logoMapType = { [key: string]: FC<SVGProps<SVGSVGElement>> };
const logoTypesMap: logoMapType = {
facebookLogo: FacebookLogo,
twitterLogo: TwitterLogo,
instagramLogo: InstagramLogo,
youtubeLogo: YoutubeLogo,
arrowUp: ArrowUp,
arrowDown: ArrowDown,
};
const SvgExporter = (logoName: string) => {
let Logo = logoTypesMap[logoName];
return <Logo />;
};
export default SvgExporter;
当我在一个组件中使用我的SvgExporter
时,我收到此类型的错误:
TS2322: Type '{ logoName: string; }' is not assignable to type 'string'.
<div className="flex justify-center flex-1 w-[55px] ">
<SvgExporter logoName={card.icon} />
</div>
card.icon
是一个字符串,所以当我传递一个字符串到SvgExporter
,匹配logoTypesMap
,并返回正确的svg。
但是我很难理解类型错误消息。
当我尝试键入SvgExporter
函数参数到{ logoName: string }
时,我得到这个错误:TS2538: Type '{ logoName: string; }' cannot be used as an index type.
1条答案
按热度按时间pb3skfrl1#
第一个参数应该是一个对象类型。然后您可以将其反结构化: