【发布时间】:2022-01-24 19:07:49
【问题描述】:
我在设置 Card.Img 元素的 src 时遇到问题,这个元素是通过 .map() 生成的,它从数组中映射对象的道具,让我告诉你:
const items = [
{name:"Banana",price:4,img : './imgShop/pexels-any-lane-5945848.jpg',id:1},
{name:"Apple",price:2,img : './imgShop/pexels-bruno-scramgnon-575610.jpg',id:2},
{name:"Orange",price:4,img : './imgShop/pexels-dominika-roseclay-2090902.jpg',id:3},
{name:"Lemon",price:3,img : './imgShop/pexels-lukas-1414110.jpg',id:4},
{name:"Pumpkin",price:10,img : './imgShop/pexels-miguel-á-padriñán-673073.jpg',id:5},
{name:"Kiwi",price:5,img : './imgShop/pexels-pixabay-51312.jpg',id:6},
{name:"Green apple",price:3,img : './imgShop/pexels-pixabay-533343.jpg',id:7},
{name:"Cherry",price:1,img : './imgShop/pexels-lisa-109274.jpg',id:8},
{name:"Guacamole",price:7,img : './imgShop/pexels-dominika-roseclay-2095924.jpg',id:9},
{name:"Melon",price:12,img : './imgShop/pexels-brian-van-den-heuvel-1313267.jpg',id:10},
{name:"Pomegranate",price:9,img : './imgShop/pexels-karolina-grabowska-4226732.jpg',id:11},
{name:"Pear",price:2,img : './imgShop/pexels-mali-maeder-568471.jpg',id:12},]
和
const Shop = () => {
let firstArray = items.slice(0,4)
let secondArray = items.slice(4,8)
let thirdArray = items.slice(8)
return(
<div id="shop-container" className="container d-flex">
<div className="col">
{firstArray.map(item => {
return(
<Card style={{ width: '18rem' }} key={item.id}>
<Card.Img variant="top" src={require(item.img)} />
<Card.Body>
<Card.Title>{item.name}</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up the bulk of
the card's content.
</Card.Text>
</Card.Body>
</Card>
)
})}
</div>
<div className="col">
</div>
<div className="col">
</div>
</div>
)
}
我已经尝试只放置一个图像的路径并且可以工作,但是当我放置 item.img 时会抛出该错误,我必须使用 require 函数因为如果不是 webpack 就不会处理 img
【问题讨论】:
标签: javascript reactjs webpack