问题
Question about using images in React!
Importing a pic and then using it works:
import photo from "../img/profilephoto.jpg"
<img src={photo} />
Using props as the source inside a require() works:
<img src={require(`../img/${this.props.img}`)} />
But importing an object (with more objects), and then using navigation to get a string, does not work!
import text from "../text" // This is the object wich contains more objects
<img src={require(`../img/${text.contact.photo}`)} />
Error because "text is not defined".
I've looking for answer on the internet, but I can't find a solution for an imported object. Is it possible to use a key/value in an imported object as a path source for an img, where the img itself is not previously imported?
回答1:
The problem is solved!
Before
I had it like this in text.js; just objects:
export default {
header: {
key: "value,
key: "value",
photo: "./img/photo.jpg"
},
footer: {
...and so on...
}
}
And in the component i had this:
import text from "../text" // This is the object wich contains more objects
<img src={require(`../img/${text.contact.photo}`)} />
After
In order for the require() to work, the photo needs to be known. So I changed to this in the text.js:
*import photo from "./img/photo.jpg"* //This import is new
export default {
header: {
key: "value,
key: "value",
photo: *photo* //Use the imported phto instead of writing the file path
},
footer: {
...and so on...
}
}
And in the component:
<img src={text.contact.photo}/> //Using the text.js with the objects
And now it works!!
Thanx for feedback!
来源:https://stackoverflow.com/questions/50310782/images-in-react-is-it-possible-to-use-a-string-from-an-imported-object-as-the-s