如何在reactjs中映射图像 [英] How to map images in 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( 为什么起作用?: Webpack可以通过生成有关目录和扩展名的上下文来理解该表达式,并可以加载所有匹配的模块./p> So in a Reactjs class component, I have an array in my state like this: and I mapped the array this way: 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 And to render at UI (add directory path and the extension inside Why it works?: Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules. 这篇关于如何在reactjs中映射图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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>))}
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' },
]
{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>
))}
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',
},
]
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>
))}