我有一个小问题。我不知道如何动态地传递这些本地图像。
比方说我有API,它返回类似的静态6存储模式。
stores: [{id:1, name: "Wallmart"}, {id: 2, name: "Amazon"}];
我有一些名为store1.jpg、store2.jpg 所以我需要根据id动态循环这些图像。 所以,我的问题是怎样做才是最好的方法。也许我可以创建一些包含所有图像的对象,或者像那样导入所有图像。我没有检查这个版本,也许它根本不起作用。这看起来不太合适。有人能给我一些有经验的建议吗?import store1 from "./store1.jpg"
{
stores.map((store) => (
<img src={`store${store.id}`} />
)
}
忘记导入图像,直接使用stores.map
函数中的图像路径。
<img src={"store" + store.id + ".jpg"} />
我发现了这种类型的解决方案,因为我发现我也有颜色。我将所有图像添加到public/images文件夹
export const stores : any = {
store1:{
id: 1,
src: "/images/store1.png",
tertiary: "#000",
primary: "#FFF",
},
store2:{
id: 2,
src: "/images/store2.png",
tertiary: "#999",
primary: "#aaa",
}
...
}
所以我导入存储并像那样循环。
import {stores} from "./constants"
{
store.map((item:any) => (
<StoreCatalogCard
title={item.name}
img={stores[`store${item.id}`].src}
primaryColor={stores[`store${item.id}`].primary}
tertiaryColor={stores[`store${item.id}`].tertiary}
light={true}
/>
))
}