按名称从react-icons获取图标

问题描述

我正在创建一个私有的React组件库,并且希望通过简单提供名称(无论如何已经由iconType作为前缀)来使用react-icons中的任何图标。所以我创建了以下组件:

import React,{ useEffect } from 'react';
import PropTypes from 'prop-types';
import { IconContext } from 'react-icons';

export const Icon = ({name,style}) => {
    let IconElement = null;

    const setIcon = (name) => {
        const iconType = name.match(/(^.[a-z]+)/)[0];

        try { 
            IconElement = require(`react-icons/${iconType.toLowerCase()}/`)[name] || null;
        } catch(e) {
            console.error(e);
        }
    }

    useEffect(() => {
        if (name) setIcon(name);
    },[name]);
    
    return (
        <IconContext.Provider value={{ style }}>
            <div>hi
                {IconElement}
            </div>
        </IconContext.Provider>
    );
};

Icon.propTypes = {
    name: PropTypes.string.isrequired,style: PropTypes.shape({
        fontSize: PropTypes.string,color: PropTypes.string,}),};

Icon.defaultProps = {
    name: 'FaChessBoard',};

但是在我的故事书中这样称呼时:

import React from 'react';

import { Icon } from './Icon';

export default {
  title: 'Example/Icon',component: Icon,};

const Template = (args) => <Icon {...args} />;

export const Default = Template.bind({});
Default.args = {
  name: ''
};

export const MaterialDesignIcons = Template.bind({});
MaterialDesignIcons.args = {
  name: 'MdInsertComment'
};

export const FontAwesomeIcons = Template.bind({});
FontAwesomeIcons.args = {
  name: 'FaAddressCard'
};

它没有被渲染。有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)