如何将自有商品数组转换为pro-gallery库要求的图片对象数组格式
商品数组转pro-gallery要求格式实现方案
字段映射关系
itemId取原商品数组的_id字段mediaUrl取原商品数组的image字段metaData.title取原商品数组的name字段metaData.description取原商品数组的description字段metaData.type固定写为image- 原数组无图片宽高字段,可根据需求选择填默认值或预加载图片获取真实宽高
基础同步实现(使用默认宽高)
如果对图片展示精度要求不高,直接使用默认宽高即可,pro-gallery会自动适配图片比例:
// 假设原商品数据存储在products变量中 const galleryItems = products.map(product => ({ itemId: product._id, mediaUrl: product.image, metaData: { type: "image", width: 100, height: 100, title: product.name, description: product.description } }))
异步实现(获取真实图片宽高)
如果需要传入图片真实宽高,可通过预加载图片的方式获取:
const generateGalleryItems = async (products) => { const result = [] for (const product of products) { const img = new Image() img.src = product.image // 等待图片加载完成获取宽高 await new Promise((resolve) => { const pushItem = (width = 100, height = 100) => { result.push({ itemId: product._id, mediaUrl: product.image, metaData: { type: "image", width, height, title: product.name, description: product.description } }) resolve() } img.onload = () => pushItem(img.naturalWidth, img.naturalHeight) img.onerror = () => pushItem() // 加载失败用默认值 }) } return result } // 调用方式 const galleryItems = await generateGalleryItems(products)
内容的提问来源于stack exchange,提问作者Guillaume Ayad
相关产品推荐
相关产品推荐

