Javascript 如何在react中使用require()和变量名?

Javascript 如何在react中使用require()和变量名?,javascript,reactjs,Javascript,Reactjs,我读过很多关于堆栈溢出和博客的解决方案,但没有一个能解决我的问题。 我有来自api的图像URL。这很少见,但这是我的任务 productsdata= { id: 12, title: "Cat Tee Black T-Shirt", description: "4 MSL", availableSizes: ["S", "XS"], style: "Black with custom print",

我读过很多关于堆栈溢出和博客的解决方案,但没有一个能解决我的问题。 我有来自api的图像URL。这很少见,但这是我的任务

   productsdata= {
        id: 12,
        title: "Cat Tee Black T-Shirt",
        description: "4 MSL",
        availableSizes: ["S", "XS"],
        style: "Black with custom print",
        price: 10.9,
        installments: 9,
        currencyId: "USD",
        currencyFormat: "$",
        isFreeShipping: true,
        src_1: "../../assets/113_1.jpg",
        src_2: "../../assets/113_2.jpg"
      },
在这里,我将图像显示为

{productsdata.map(product => {
        return (
          <>
            <img src={product.src_1} width="200" height="200" alt="tshirt" />
            {/* <img src={product.src_2} width="200" height="200" /> */}
          </>
        );
      })}
{productsdata.map(产品=>{
返回(
{/*  */}
);
})}
但是它不能像
require()
那样只适用于静态url。
有人能帮我吗?

你应该这样用-

import React,{useState}来自“React”;
从“./旧”进口产品;
const New=(道具)=>{
返回(
{Products.map((Product,i)=>(
Object.values(Product.map)((prod,i)=>(
id:{prod.id}

类别:{prod.category}

文件名:{prod.filename}

名称:{prod.name}

价格:{prod.price}

)) ) )} ); }
导出新的默认值我将图像URL更改为

 productsdata= {

        src_1: "113_1.jpg",
        src_2: "113_2.jpg"
      },
并将“src”属性更改为

 <img src={require(`../../assets/${product.src_1}`)} width="200" height="200" alt="tshirt" />


它工作得很好。这里还需要使用变量和动态url。世上有谁会想到这样写。我认为这是javascript中的一个错误,或者我没有足够的理解:p

请发布生成
元素的ReactJS代码。如果JSX中有api响应,请使用大括号。api中的img路径如何可以是相对路径?似乎很奇怪。请他们修复API响应,因为在响应中发送相对URL是没有意义的。其中old.js文件看起来是这样的=====>const Products=[{“867850”:{“id”:“867850”,“category”:“衣服”,“filename”:“钱包”,“name”:“钱包”,“price”:45.48}];出口默认产品;我不明白。这如何解决我在呈现imageUse var Products=require('./old')时遇到的问题;并将Products.map更改为=>Products.default.map谢谢您的关心,但我不明白您在说什么