reactjs 无法获取SVG组件的正确类型

z31licg0  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(139)

我有一个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.

pb3skfrl

pb3skfrl1#

第一个参数应该是一个对象类型。然后您可以将其反结构化:

const SvgExporter = ({ logoName }: { logoName: string }) => {
  let Logo = logoTypesMap[logoName];
  return <Logo />;
};

相关问题