react 图片绝对路径,动态导入图像(React Js)(需要img路径找不到模块)

I need to import images(several) from my image file dynamically by a map method. First, I want to set a base URL to my images file and then read the image's name from my JSON file which includes the image property and then set the image src accordingly.

The JSON file is like below :

{

"title": "Blue Stripe Stoneware Plate",

"brand": "Kiriko",

"price": 40,

"description": "Lorem ipsum dolor sit amet...",

"image": "blue-stripe-stoneware-plate.jpg"

},

{

"title": "Hand Painted Blue Flat Dish",

"brand": "Kiriko",

"price": 28,

"description": "Lorem ipsum dolor sit amet...",

"image": "hand-painted-blue-flat-dish.jpg"

},

my images folder : lSSSX.png

I have read the products by redux which is works perfectly =>

const products = this.props.products;

console.log(products, 'from redux');

const fetchProducts = [];

for (let key in products) {

fetchProducts.push({

...products[key]

});

}

the console.log() => H8w72.png

Now I want to define a base URL like this which later use as image src by adding the image's name from the JSON file in the map method :

const baseUrl = '../../components/assets/images/';

const fetchProducts = [];

for (let key in products) {

fetchProducts.push({

...products[key]

});

}

const productCategory = fetchProducts.map((product, index) => {

return (

key={index}

title={product.title}

brand={product.brand}

description={product.description}

imageSource={baseUrl + product.image}

imageAlt={product.title}

/>

);

});

my Photo component looks like below :

const photo = props => (

{props.imageAlt}

{props.brand}

{props.title}

{props.price}

);

export default photo;

unfortunately, I have faced this error: Xz4QQ.png

Thanks in advance and sorry for my bad English :)

解决方案

Import is not working like that. You can use a base URL like that:

const baseUrl = "../../components/assets/images/";

Then you can pass to your Photo component like that:

key={index} // Don't use index as a key! Find some unique value.

title={product.title}

brand={product.brand}

description={product.description}

imageSource={baseUrl + product.image}

imageAlt={pro.title}

/>;

Lastly, in your Photo component use require:

{props.imageAlt}

or like that:

{props.imageAlt}

But, don't skip "" part or don't use it directly like:

foo

since require wants an absolute path string and first two do this trick.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值