我在設定 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
uj5u.com熱心網友回復:
你可以像這樣一一匯入
import image1 from "./imgShop/pexels-any-lane-5945848.jpg";
import image2 from "./imgShop/pexels-bruno-scramgnon-575610.jpg";
..........
然后使用image1,image2在你的items陣列中img:{image1}
或者
您可以創建一個新的 js 檔案來為您匯出這些影像。
import image1 from './imgShop/pexels-any-lane-5945848.jpg';
import image2 from './imgShop/pexels-bruno-scramgnon-575610.jpg';
export default [
image1,
image2,
];
然后在你的主 js 檔案中匯入
import imagesArray from './images';
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/392977.html
標籤:javascript 反应 网络包
