如何根据动态数据的反应将图像加载到页面上? [英] How to load an image onto the page with react from dynamic data?

查看:98
本文介绍了如何根据动态数据的反应将图像加载到页面上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序页面上显示图像

I want to display an image on my react app page

import egypt from '../images/egypt.svg'

<div>
   <img src={egypt}/>
</div>

这是正确的方法吗?

我也想从这样的对象中加载它:

Also I want to load it in from an object like this:

options: [{
       optionOne: {
         answer: 'bolivia',
         image: './images/egypt.svg'
       }
     }]

如何在屏幕上显示它?

我的错误是说我需要一个合适的装载器.我尝试使用此方法: https://www.npmjs.com/package/image- webpack-loader

my error is saying I need an appropriate loader. I tried to use this: https://www.npmjs.com/package/image-webpack-loader

但是它说: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'
    ]
  }

推荐答案

如果

import egypt from '../images/egypt.svg'

<div>
   <img src={egypt}/>
</div>

在您的代码中正常工作,并且您已经正确配置了Webpack,通过在模板文字(如

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}`)}

还要确保使用命令安装url loader

Also make sure you install url loader with command

npm install -s url-loader

您需要将webpack配置为url-loader

 {
        test: /\.(jpe?g|png|gif|svg)$/,
        use:['url-loader']
    }

这篇关于如何根据动态数据的反应将图像加载到页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆