1

我有下面的图标如下

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} />;
})}
4

1 回答 1

0

试试这个方法,

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

于 2020-11-21T16:07:04.543 回答