How to use require() with variable names in react?

白昼怎懂夜的黑 提交于 2021-02-11 16:51:48

问题


I have read many solutions on stack overflow and blogs but none could solve my problem. I have image urls from api. It is uncommon but it is an assignment to me

   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"
      },

here I am displaying image as

{productsdata.map(product => {
        return (
          <>
            <img src={product.src_1} width="200" height="200" alt="tshirt" />
            {/* <img src={product.src_2} width="200" height="200" /> */}
          </>
        );
      })}

but it doesn't work as require() only works with static url. Could someone pls help me?


回答1:


you should use like this-

import React, {useState} from 'react';
    import Products from './old';
 const New = (props) =>{
    
    return(
        <div>
       {Products.map((Product, i)=>(
         Object.values(Product).map((prod, i) => (
            <div key={i}>
                <p>id: {prod.id}</p>
                <p>category: {prod.category}</p>
                <p>filename: {prod.filename}</p>
                <p>name: {prod.name}</p>
                <p>price: {prod.price}</p>
            </div>
          )) 
       )

       )}
        </div>
    );
}
export default New;



回答2:


I changed the image urls as

 productsdata= {

        src_1: "113_1.jpg",
        src_2: "113_2.jpg"
      },

and changed the 'src' attribute as

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

It worked fine. Here also 'require' is using variable and dynamic url. Who on the earth would think of writing this way. I think it's a bug in javascript or I don't have enough understanding:p



来源:https://stackoverflow.com/questions/60111140/how-to-use-require-with-variable-names-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!