简体   繁体   English

如何在 ReactJS 中循环使用“react-icons”(Map 方法)

[英]How to use "react-icons" in loop (Map method) in ReactJS 😅

I'm using React-icons in my ReactJS project and I just wanted to loop (by Map method) the specific icons in each JSX field when data is render.我在我的ReactJS项目中使用React-icons ,我只想在呈现数据时循环(通过 Map 方法)每个JSX字段中的特定图标

In other word, I want this {`<${e.contact.icons}/>`} in JSX code.换句话说,我想要这个{`<${e.contact.icons}/>`}JSX代码中。 Here is my code section:-这是我的代码部分:-

Here is, I import some icons for React icons .在这里,我为React icons导入了一些图标

import { FaBeer, Fa500Px, FeAccusoft } from "react-icons/fa";

Here is a data array which I want to render in JSX .这是我想在JSX中呈现的数据数组

const data = [
  {
    contact: [
      {
        title: 'contact',
        icons: 'FaBeer',
      },
      {
        title: 'contact',
        icons: 'Fa500Px',
      },
      {
        title: 'contact',
        icons: 'FaAccusoft',
      },
    ],
  },
]

And this is my component in down below.这是我在下面的组件。 Which I'm using icons .我正在使用icons You get little idea what I want to do.你不知道我想做什么。

const contact = () => {
  return (
    <>
      {data.map((e, i) => {
        return (
          <>
            <div className="text-area">
              <span> {`<${e.contact.icons}/>`} </span>
            </div>
          </>
        );
      })}
    </>
  );
};

export default contact;

I'm trying to use like this {`<${e.contact.icons}/>`} , but is not working.我正在尝试像这样使用{`<${e.contact.icons}/>`} ,但没有用。 When I see in browser.当我在浏览器中看到时。 It's look like this.它看起来像这样。

<FaBeer/>
<Fa500Px/>
<FaAccusoft/>

It's just return like a text, but I want to get icons .它只是像文本一样返回,但我想获得图标

Any suggestion ?

You can also use Parser() from html-react-parser.您还可以使用 html-react-parser 中的 Parser()。 https://github.com/remarkablemark/html-react-parser https://github.com/remarkablemark/html-react-parser

const parse = require('html-react-parser');
{parse(`<${e.contact.icons}/>`)};

https://codesandbox.io/s/fervent-goldwasser-y83cn?file=/src/App.js https://codesandbox.io/s/fervent-goldwasser-y83cn?file=/src/App.js

import { FaBeer, Fa500Px, FaAccusoft } from "react-icons/fa";

// here is data for I want to show

const data = [
  {
    contact: [
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaBeer
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: Fa500Px
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaAccusoft
      }
    ]
  }
];

const contact = () => {
  return (
    <>
      {data.map((e, i) => {
        return (
          <>
            {e.contact.map((e, i) => {
              return (
                <div className="text-area" key={i}>
                  <h1 className="title">{e.title}</h1>
                  <h2 className="subtitle">{e.subtitle}</h2>
                  <span>
                    <e.icons />
                  </span>
                </div>
              );
            })}
          </>
        );
      })}
    </>
  );
};

export default contact;

It seems that the current answers already addresses the problem, so this only attempts to add small improvement for the solution.目前的答案似乎已经解决了这个问题,所以这只是尝试对解决方案进行小的改进。 Here is an approach I tried in a similar situation.这是我在类似情况下尝试过的一种方法。

Simplified demo on: stackblitz简化演示: stackblitz

This will keep data the same as posted in the question as it might need to be fetched:这将使data与问题中发布的数据相同,因为它可能需要获取:

const data = [
  {
    contact: [
      {
        title: 'contact',
        icons: 'FaBeer',
      },
      {
        title: 'contact',
        icons: 'Fa500Px',
      },
      {
        title: 'contact',
        icons: 'FaChrome',
      },
    ],
  },
];

Define an object with the imported icons as static data:定义一个 object 导入的图标为 static 数据:

import { FaBeer, Fa500Px, FaChrome } from 'react-icons/fa';
const icons = { FaBeer, Fa500Px, FaChrome };

In the output, the icon can taken out from static data, and rendered on condition:在output中,可以从static数据中取出图标,并按条件渲染:

const Contact = () => {
  return (
    <>
      {data.map((e, i) => (
        <React.Fragment key={i}>
          {e.contact.map((item, index) => {
            const Icon = icons?.[item.icons];
            return (
              <div key={index} className="text-area">
                <span>{Icon && <Icon size="3em" color="hotpink" />}</span>
              </div>
            );
          })}
        </React.Fragment>
      ))}
    </>
  );
};

export default contact;

Well, the option of importing FaIcon-s and putting them into "data" array looks pretty nice:好吧,导入 FaIcon-s 并将它们放入“数据”数组的选项看起来很不错:

import { FaBeer, Fa500Px, FaAccusoft } from "react-icons/fa";

const data = [
  {
    contact: [
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaBeer,
      },
...

On the other hand possibility of generating components "dynamically" by their string name could be still implemented.另一方面,仍然可以实现通过字符串名称“动态”生成组件的可能性。

Firstly, I find usefull following article: React / JSX Dynamic Component Name首先,我发现以下文章很有用: React / JSX Dynamic Component Name

Next, I've created a new FaIconDynamic component:接下来,我创建了一个新的 FaIconDynamic 组件:

import {
    AiFillAccountBook,
    AiFillAlert,
    AiFillAlipayCircle,
    AiFillAndroid,
} from 'react-icons/ai';

export const FaIconDynamic = ({ type }) => {
    const FaIcon = components[type];
    return <FaIcon></FaIcon>;
};

const components = {
    AiFillAccountBook,
    AiFillAlert,
    AiFillAlipayCircle,
    AiFillAndroid,
};

And then that's pretty easy to generate any registered above fa-icon, fe:然后很容易生成任何在上面注册的 fa-icon,fe:

function App() {
    return (
        <>
            <FaIconDynamic type={'AiFillAccountBook'} />
            <FaIconDynamic type={'AiFillAlert'} />
            <FaIconDynamic type={'AiFillAlipayCircle'} />
            <FaIconDynamic type={'AiFillAndroid'} />
        </>
    );
}

Of course, both approaches have their pros and cons and could be more benefitial in some situations over each other当然,这两种方法各有利弊,并且在某些情况下可能比彼此更有利

You cannot use strings to represent React Component Types, instead you can use the imported ComponentType itself.您不能使用字符串来表示 React 组件类型,而是可以使用导入的 ComponentType 本身。

import { FaBeer, Fa500Px, FaAccusoft } from "react-icons/fa";

// here is data for I want to show

const data = [
  {
    contact: [
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaBeer,
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: Fa500Px,
      },
      {
        title: "contact",
        subtitle: "get in touch",
        icons: FaAccusoft,
      },
    ],
  },
];

const Contact = () => {
  return (
    <>
      {data.map((e, i) => {
        const Icon = e.contact.icons;
        return (
          <>
            <div className="text-area">
              <h1 className="title">{e.contact.title}</h1>
              <h2 className="subtitle">{e.contact.subtitle}</h2>
              <span><Icon /></span>
            </div>
          </>
        );
      })}
    </>
  );
};

export default Contact;

Note how the rendering of Icon changes as well请注意Icon的呈现方式也发生了变化

I have gotten this type of method and I manage to do what I want我已经得到了这种方法并且我设法做我想做的事

import React from "react";
import { render } from "react-dom";
import * as FontAwesome from "react-icons/lib/fa";

const Icon = props => {
  const { iconName, size, color } = props;
  const icon = React.createElement(FontAwesome[iconName]);
  return <div style={{ fontSize: size, color: color }}>{icon}</div>;
};

const App = () => {
  const iconString = "FaBeer";
  const beer = React.createElement(FontAwesome[iconString]);
  return (
    <div>
      <h2>Start editing to see some magic happen {"\u2728"}</h2>
      <FontAwesome.FaBeer />
      <div style={{ fontSize: 24, color: "orange" }}>{beer}</div>
      <Icon iconName={"FaBeer"} size={12} color="orange" />
    </div>
  );
};


----------


render(<App />, document.getElementById("root"));

https://codesandbox.io/s/o715x22m4z?file=/src/index.js:0-737`enter code here` https: //codesandbox.io/s/o715x22m4z?file=/src/index.js:0-737`在此处输入代码`

thank to〈Evie.Codes〉.感谢〈Evie.Codes〉。

import { FaBeer, Fa500Px, FeAccusoft } from "react-icons/fa";从“react-icons/fa”导入{FaBeer、Fa500Px、FeAccusoft};

note: there is a typo in the name of the icon you imported.. it should be FaAccusoft注意:您导入的图标名称中有错字。应该是FaAccusoft

my suggestion for your question is to store the Icon components themselves in the object property.. so instead of storing it as string: "FaBeer" ... store it as a component: <FaBeer /> directly inside the object property.. like this:我对你的问题的建议是将 Icon 组件本身存储在 object 属性中。所以不要将其存储为字符串: “FaBeer” ...将其存储为组件: <FaBeer />直接在 object 属性中......就像这个:

const data = [
  {
    contact: [
      {
        title: "contact-1",
        icons: <FaBeer />
      },
      {
        title: "contact-2",
        icons: <Fa500Px />
      },
      {
        title: "contact-3",
        icons: <FaAccusoft />
      }
    ]
  }
];

and then you can simply loop over them然后你可以简单地遍历它们

const Contact = () => {
  return (
    <>
      {data.map((e, i) => {
        return (
          <>
            {e.contact.map((c) => {
              return (
                <div className="text-area">
                  {c.title}
                  <span>
                    {c.icons} // you simply call it like this and the icon will be rendered
                  </span> 
                </div>
              );
            })}
          </>
        );
      })}
    </>
  );
};

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

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