【问题标题】:Using Icons in React在 React 中使用图标
【发布时间】:2021-03-04 18:05:49
【问题描述】:

我有下面的图标如下

import GandalfIcon from "../../assets/gandalf.svg";
import TreasureMapIcon from "../../assets/treasuremap.svg";
import BookIcon from "../../assets/book.svg";
import AcademyIcon from "../../assets/academy.svg";

我在 JSON 文件中也有相同的名称(GandalfIcon、TreasureMapIcon...)。我想要做的是当我从 JSON 中获取字符串“GandalfIcon”时,我想在页面上显示实际的 GandalfIcon。我正在使用 map() 所以我想我不能对它们进行硬编码,并且使用 {} 不起作用。有什么建议吗?

所以澄清一下,这是行不通的:

{event.icons.map((icon) => {
    const url = icon;
    return <img src={url} />;
})}

【问题讨论】:

    标签: reactjs icons map-function react-icons


    【解决方案1】:

    试试这个方法,

    import React from "react";
    import "./styles.css";
    import GandalfIcon from "../public/image-1.png";
    import TreasureMapIcon from "../public/image-2.png";
    import BookIcon from "../public/image-1.png";
    import AcademyIcon from "../public/image-2.png";
    
    const imageArray = [
      { GandalfIcon },
      { TreasureMapIcon },
      { BookIcon },
      { AcademyIcon }
    ];
    export default function App() {
      const event = {
        icons: ["GandalfIcon", "TreasureMapIcon", "BookIcon", "AcademyIcon"]
      };
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          {event.icons.map((icon) => {
            const url = imageArray.find((img) => img[icon])[icon];
            return <img src={url} alt="" />;
          })}
        </div>
      );
    }
    

    希望这是您正在寻找的用例。

    示例代码 - https://codesandbox.io/s/fervent-goldberg-qlz1f?file=/src/App.js:0-713

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 2021-05-08
      • 2018-11-22
      • 2019-05-04
      • 2018-02-19
      • 2020-10-07
      • 2021-05-22
      • 2021-01-30
      相关资源
      最近更新 更多