如何在reactjs中映射图像 [英] How to map images in reactjs

查看:45
本文介绍了如何在reactjs中映射图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在Reactjs类组件中,我的状态如下:

  myArray:[{number:1,title:'Users',image:'../../../assets/images/website/homepage/users.png'},{number:2,title:'Clients',image:'../../../assets/images/website/homepage/clients.png'},{数字:3,标题:'Admin',图片:'../../../assets/images/website/homepage/admins.png'},] 

然后我这样映射数组:

  {this.state.myArray.map((item,index)=>(< Box键= {index} className ="col-sm-12">< img src = {item.image} className ="img-fluid" alt = {item.title}/>< Typography variant ="h4"> {item.number}</Typography></Box>))} 

现在,一切正常,除了没有显示的图像,我真的不明白我在哪里弄错了.

请注意,如果我使用require方法直接在src内部复制图像链接之一,则它可以工作.请帮助.

解决方案

您可以

并渲染到UI( require 内部的添加目录路径扩展名):

  {myArray.map((item,index)=>(< Box键= {index} className ="col-sm-12">< imgsrc = {require('../../../assets/images/website/homepage/'+item.image +'.png')}className ="img-fluid"alt = {item.title}/>< Typography variant ="h4"> {item.number}</Typography></Box>))} 

为什么起作用?:

Webpack可以通过生成有关目录和扩展名的上下文来理解该表达式,并可以加载所有匹配的模块./p>

So in a Reactjs class component, I have an array in my state like this:

myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]

and I mapped the array this way:

{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">
      <img src={ item.image } className="img-fluid" alt={item.title} />
      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}

Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

解决方案

You can require dynamically with proper expression:

Change image to (remove ../../../assets/images/website/homepage/ and .png):

const myArray = [
  {
    number: 1,
    title: 'Users',
    image: 'users',
  },
  {
    number: 2,
    title: 'Clients',
    image: 'clients',
  },
  {
    number: 3,
    title: 'Admin',
    image: 'admins',
  },
]

And to render at UI (add directory path and the extension inside require):

{myArray.map((item, index) => (
  <Box key={index} className="col-sm-12">
    <img
      src={require('../../../assets/images/website/homepage/' +
        item.image +
        '.png')}
      className="img-fluid"
      alt={item.title}
    />
    <Typography variant="h4">{item.number}</Typography>
  </Box>
))}

Why it works?:

Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.

这篇关于如何在reactjs中映射图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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