【问题标题】:I want to component that can change the icon to be displayed according to the name of the icon我想要一个可以根据图标名称更改要显示的图标的组件
【发布时间】:2021-03-26 07:17:58
【问题描述】:

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

index.tsx

<Icon icon="twitter"/>

图标.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>
    );

【问题讨论】:

    标签: reactjs typescript chakra


    【解决方案1】:

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

    图标.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 }} />;
    };
    

    【讨论】:

    • 图标不显示。
    • 我导入了每个图标,但显示错误消息。
    • 'Twitter' 被声明但它的值从不 read.ts。'Linkedin' 被声明但它的值从不 read.ts。'Facebook' 被声明但它的值从不 read.ts。
    • 这个刚刚更新的sn-p已经可以使用了,你可以试试。
    • 组件函数从来没有被读取的原因,我猜是在编译的时候被移除了,所以我用一个对象来恢复它们。
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多