问题
I want to display an image on my react app page
import egypt from '../images/egypt.svg'
<div>
<img src={egypt}/>
</div>
Is this the correct way to do this?
Also I want to load it in from an object like this:
options: [{
optionOne: {
answer: 'bolivia',
image: './images/egypt.svg'
}
}]
how can I display it on screen?
my error is saying I need an appropriate loader. I tried to use this: https://www.npmjs.com/package/image-webpack-loader
but it says: Can't resolve 'file-loader'
{
test: /\.svg$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
回答1:
If
import egypt from '../images/egypt.svg'
<div>
<img src={egypt}/>
</div>
works in your code and you have configured the webpack properly, you would be able to dynamically display the image in React by requiring them with the help of template literals like
<img src={require(`${obj.optionOne.img}`)}
Also make sure you install url loader
with command
npm install -s url-loader
You need to configure your webpack
with url-loader
as
{
test: /\.(jpe?g|png|gif|svg)$/,
use:['url-loader']
}
来源:https://stackoverflow.com/questions/45287748/how-to-load-an-image-onto-the-page-with-react-from-dynamic-data