简体   繁体   English

导入动态反应图标

[英]import dynamically react icons

I need to import a icon dynamically with the props will receive in the component and return the icon compatible with this, i have a question about this:我需要动态导入一个图标,道具将在组件中接收并返回与此兼容的图标,我对此有疑问:

import { useEffect, useState } from 'react';

export default function Icon({ libraryName, iconName }) {
  const [icon, setIcon] = useState(null);

  async function getIcon() {
    const path = `../../../node_modules/react-icons/${libraryName}`;
    const returnedIcon = await import(path);
    if (returnedIcon) setIcon(returnedIcon[iconName]);
  }

  useEffect(() => {
    if (iconName) {
      getIcon();
    } else {
      setIcon(null);
    }
  }, []);

  return <span>{icon}</span>;
}


So, if you call this component for example with this所以,如果你用这个来调用这个组件

<Icon libraryName="md" iconName="mdMonitor" />

This work!这个作品!

But, maybe the const path can be change with another path?但是,也许 const 路径可以用另一条路径更改?

I think that exist better way to do this, if any can help me i would be grateful.我认为存在更好的方法来做到这一点,如果有人可以帮助我,我将不胜感激。

You shouldn't be referencing node_modules from within your components.您不应该从组件中引用node_modules Your eventual production build will not have access to that directory, because the bundler (like webpack) will package up all of your various code and library files into a single JS file.您最终的生产构建将无法访问该目录,因为捆绑器(如 webpack)会将您所有的各种代码和库文件 package 合并到一个 JS 文件中。

If you're using an icon library, you should import the icons just as you would any other JS module, and use them as you need.如果您使用的是图标库,则应该像导入任何其他 JS 模块一样导入图标,并根据需要使用它们。

If you need icons from multiple icon libraries, you'll need to npm install both libraries, and then in your UI code just import the ones you need from each library.如果您需要来自多个图标库的图标,则需要npm install这两个库,然后在您的 UI 代码中从每个库中导入您需要的图标。

Maybe you need a wrapper for your icon:也许您需要一个图标包装器:

import React from 'react';

export default function IconWrapper({icon}) {

  return <span>{icon}</span>;
}


and your UI code could look like this:您的 UI 代码可能如下所示:

import React from 'react';
import {PlusIcon} from 'icon-lib-A';
import {MinusIcon} from 'icon-lib-B';

export default function App() {
  return (
    <div>
      <Icon icon={<PlusIcon} />
      <Icon icon={<MinusIcon} />
    </div>
  )
}

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

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