繁体   English   中英

如何为支持的图像制作类型

[英]How can I make a Type for supported images

客户只是想让我用支持的图标名称制作一个类型。 我是 typescript 的新手,正在努力做到这一点。

这是我的 SVG 组件。 我在这个组件中有超过 100+ svg。

自定义图标.tsx

import { IconTypes } from "../../types/types";

const CustomIcons = (props: IconTypes) => {


  const icons: any = {
    FrameIcon: (
      <svg
        name="FrameIcon"
        width="632"
        height="330"
        viewBox="0 0 632 330"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491 475.861 332.973 430.087 327.163C395.247 322.751 361.653 311.801 333.32 293.793C312.276 280.425 293.787 263.92 275.899 246.561C252.488 223.823 227.286 203.264 202.496 182.058C185.037 167.12 165.098 156.661 147.85 141.479C134.342 129.581 121.111 117.121 107.991 104.784C86.5556 84.6234 64.0287 65.4171 42.9997 44.8476C28.9062 31.0539 13.4654 16.1833 0.432617 0.407227L460.923 -287.339Z"
          fill="#232323"
        />
      </svg>
    ),
VectorIcon: (
      <svg
        name="VectorIcon"
        width="632"
        height="330"
        viewBox="0 0 632 330"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
          fill="#232323"
        />
      </svg>
    ),
  };

  return <>{icons[props.name] ? icons[props.name] : undefined}</>;
};

export default CustomIcons;

因为这是一个 object typescript 编译器会自动推断类型,但在你的情况下你可以这样做:

const icons = {
  // ...your icons
}

type Icons = {[K in keyof typeof icons]: JSX.Element}

这是一个映射类型,您可以在此处查看更多相关信息

是 typescript 中关于 typeof 关键字的一些文档

还有一件事,如果您在另一个文件中(或在 React FC 之外)使用图标定义 object 会更好,因为看起来 object 定义在 React 功能组件内部,如果是这样,它将重新生成每次重新渲染,另一种选择是使用useRef钩子,但这只会使事情复杂化

希望对您有所帮助

暂无
暂无

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

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