简体   繁体   English

react-icons 的动态导入

[英]Dynamic import of react-icons

Is it possible to import dynamically react-icons if each of icon is a separate component?如果每个图标都是一个单独的组件,是否可以动态导入反应图标? My code looks like this:我的代码如下所示:

import React from 'react';

import { Icon1, Icon2, Icon3, Icon4 } from 'react-icons/ri';

const Foo = () => (
  <div className="xxx">
    <div className="y">
      <Icon1 />
    </div>
    <div className="y">
      <Icon2 />
    </div>
    <div className="y">
      <Icon3 />
    </div>
    <div className="y">
      <Icon4 />
    </div>
  </div>
);

export default Foo;

and would want it to look close to this:并希望它看起来接近这个:

import React from 'react';从“反应”导入反应;

const Buttons = () => {
  const iconsList = ['Icon1', 'Icon2', 'Icon3'];
  const renderIcon = (icon) => {
   const Icon = icon;
   return (
    <div className="y">
     <Icon />
    </div>
   )
  }

  return (
   <div className="d-flex align-items-center justify-content-end">
    {iconsList.map(icon => renderIcon(icon))}
   </div>
 )
};

export default Buttons;

The problem I face is how to make the import of icons work there if I didn't want to import all icons using * .我面临的问题是,如果我不想使用*导入所有图标,如何使图标的导入在那里工作。 Also the problem is that if I make还有一个问题是,如果我让


import { Icon1, Icon2, Icon3, Icon4 } from 'react-icons/ri'

at the top, it still doesn't work for the second version of code.在顶部,它仍然不适用于第二版代码。

You have to replace the strings values of your icons in the iconsList array with the Icon component itself.您必须将iconsList数组中图标的字符串值替换为 Icon 组件本身。

Just change:只是改变:

const iconsList = ['Icon1', 'Icon2', 'Icon3'];

to:至:

const iconsList = [Icon1, Icon2, Icon3];

And add a key to prevent Each child in a list should have a unique "key" prop.并添加一个键来防止Each child in a list should have a unique "key" prop. Warning like this:像这样的警告

{iconsList.map((icon, index) => renderIcon(icon, index))}

and:和:

const renderIcon = (icon, index) => {
    const Icon = icon;
    return (
      <div className="y" key={index}>
        <Icon />
      </div>
    );
  };

this is an example in codesandbox这是codesandbox中的一个例子

Note: If you import all icons using * , you're importing hundreds of icons at once which is probably not ideal.注意:如果您使用*导入所有图标,您将一次导入数百个图标,这可能并不理想。

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

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