我想要一个可以根据图标名称更改要显示的图标的组件

I want to component that can change the icon to be displayed according to the name of the icon

我正在使用 typescript、react 和 chakra ui。
我们想在给Icon组件的IconProps传递"twitter"时显示Twitter.ts的Icon组件,在传递"LinkedIn"时显示LinkedIn组件。
我想根据传递给 Icon 组件的名称更改要显示的图标。

index.tsx

<Icon icon="twitter"/>

Icon.ts


type Props = {
icon: string;
  fontSize?: string;
};

export const Icon: React.FunctionComponent<Props> = ({ icon,ontSize }) => (
return ()
);

Facebook.ts

import { Icon } from '@chakra-ui/react';
import React from 'react';

type Props = {
  fontSize?: string;
};

export const FacebookIcon: React.FunctionComponent<Props> = ({ fontSize }) => (
  <Icon fontSize={fontSize}>
    <path
      fillRule="evenodd"
      clipRule="evenodd"
      d=""//  It's a long story, so I'll skip it.
    />
  </Icon>
);
```

Linkedin.ts

    import { Icon } from '@chakra-ui/react';
    import React from 'react';

    type Props = {
      fontSize?: string;
    };
    
    export const LinkedinIcon: React.FunctionComponent<Props> = ({ fontSize }) => (
      <Icon fontSize={fontSize}>
        <path
          fillRule="evenodd"
          clipRule="evenodd"
          d=""//  It's a long story, so I'll skip it.
        />
      </Icon>
    );

Twitter.ts

    import { Icon } from '@chakra-ui/react';
    import React from 'react';

    type Props = {
      fontSize?: string;
    };
    
    export const TwitterIcon: React.FunctionComponent<Props> = ({ fontSize }) => (
      <Icon fontSize={fontSize}>
        <path
          fillRule="evenodd"
          clipRule="evenodd"
          d=""//  It's a long story, so I'll skip it.
          fill="#525E6D"
        />
      </Icon>
    );

将组件的名称设置为变量,然后你可以展开你想要的图标。

Icon.tsx

import React from 'react';
import FacebookIcon ...
import LinkedinIcon ...
import TwitterIcon ...

type Props = {
  icon: 'facebook' | 'linkedin' | 'twitter';
  fontSize?: string;
};

const iconMap = {
  facebook: FacebookIcon,
  linkedin: LinkedinIcon,
  twitter: TwitterIcon
}

export const Icon = ({ icon, fontSize }: Props) => {
  const CompName = iconMap[icon];

  return <CompName {...{ fontSize }} />;
};