简体   繁体   中英

local image doesn't appear using require react js

I tried to get dynamically the directory of the images using require but doesn't work

import React from 'react';
import './produto.css'


function Produto({data}) {

    const { id, name, price, score, image } = data;

    return <div className = 'produto-card-container' key = {id}>

        <div className = 'produto-card-flex'>
            <img alt = {image} src = {require(`../../Assets/${image}`)}/>
         
        </div>
    </div>
}

export default Produto;

but in my page the image appear likes this在此处输入图像描述

i tried to console the path and the image name to see what's happened My console log of the const image

super-mario-odyssey.png
produto.js:8 call-of-duty-infinite-warfare.png
produto.js:8 the-witcher-iii-wild-hunt.png
produto.js:8 call-of-duty-wwii.png
produto.js:8 mortal-kombat-xl.png
produto.js:8 shards-of-darkness.png
produto.js:8 terra-media-sombras-de-mordor.png
produto.js:8 fifa-18.png
produto.js:8 horizon-zero-dawn.png

It's necessary to indicate the type of image. In your case, it is a png.

 <img alt = {image} src = {require(`../../Assets/${image}.png`)}/>

Remember " require returns an object and image's path can be ejected from its default property".

So you must change the following code:

<img alt = {image} src = {require(`../../Assets/${image}`)}/>

To:

<img alt={image} src={require(`../../Assets/${image}.png`).default}/>

Note : If you want to use multi image formats, add imageFormat key to your json db and pass it's value as props.

{
    ...
    image: 'assassins-creed',
    imageFormat : 'jpg'
}

So if you do that, your code must be like to:

const {id, name, price, score, image, imageFormat} = data;

<img alt={image} src={require(`../../Assets/${image}.${imageFormat}`).default}/>

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM