问题
I have an array of object, with each object having an imageUrl property, but when I loop through this array to display all images, the image doesn't get rendered
I loop through the array and pass the attribute housing the image link to the image src
const ProjectData = [
{
title: "RestaurantX",
imageUrl: "../assets/images/restaurantpassport.png",
githubUrl: "",
deployUrl: "",
description: "",
tech: []
},
]
{ProjectData.map(project => {
return (
<Work borderColor={changeColor()}>
<img
src={project.imageUrl}
alt={project.title}
/>
<a className="github">
<i className="material-icons">code</i>
</a>
<a className="deploy">
<i className="material-icons">launch</i>
</a>
</Work>
)
回答1:
You can't use a relative path that points to somewhere in your project directory. Usual practice is to copy your images during your build process into a known folder in your output directory and then access them via /knownfolder/filename.png
- the leading slash makes the path relative to the root of your app.
It isn't enough to just remove the ..
as your running app can't access your project folders at run-time.
As you are using create-react-app
, you have (at least) two choices: 1) import the images using import
or 2) Put them in your /public
folder and use the PUBLIC_URL
variable.
The first approach looks like this:
import restaurantPassport from '../assets/images/restaurantpassport.png';
<img src={restaurantPassport} />;
This is probably the one for you (see here for more detail), but if you want to go the other way it's covered here in the docs.
回答2:
You could use require
.
Something like this -
const ProjectData = [
{
...
imageUrl: require("../assets/images/restaurantpassport.png"),
...
},
]
回答3:
I was able to get it to work, in a way, I won't say is ideal, but works. I just had to make this change to ProjectData array
.
{
title: "RestaurantX",
imageUrl: require("../assets/images/restaurantpassport.png"),
githubUrl: "",
deployUrl: "",
description: "",
tech: []
},
]
来源:https://stackoverflow.com/questions/56856500/how-to-display-an-image-from-an-array-of-images-in-react