How to load an image onto the page with react from

2019-08-08 03:20发布

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条回答
不美不萌又怎样
2楼-- · 2019-08-08 03:57

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']
    }
查看更多
登录 后发表回答