javascript - 如何在 React 中循环渲染图像?
问题描述
我正在尝试创建一张带有标题、描述和图像的卡片。
我的文件结构如下:
src
-components
-images
-section
-Featured.js
在 config.js 文件中,我有:
module.exports = {
featuredSection: [
{
name: 'beer-image-1',
title: 'Mango Cart',
description:
'A light Wheat Ale bursting with lots of
fresh mango flavor and aroma, finishing
crisp and refreshing.',
},
],
};
在我的Featured.js
组件文件中,我尝试过:
const Featured = () => {
...
// Get array of all names in config file
const featuredNames = featuredSection.map((beer) => beer.name); // --> ['beer-image-1']
// Return an image for each name in `featuredNames` array
const images = featuredNames.map((image) => {
return (
<img
key={image}
src={require(`../images/${image}.jpg`)}
alt='Beer picture'
/>
);
});
// Return title, desc., and image
const card = featuredSection.map((image, i) => {
return (
<div key={i}>
<h1>{image.title}</h1>
<p>{image.description}</p>
{images}
</div>
);
});
return <>{card && card}</>;
}
这将返回标题和描述,但图像未加载,仅显示替代文本。
我一直在尝试使用这些示例,但它总是导致出现替代文本。
解决方案
您可以将文件夹移动images
到public
文件夹吗?如果可以,下面的代码应该可以工作
<img
key={image}
src={`./images/${image}.jpg`}
alt='Beer picture'
/>
如果您无法移动images
文件夹,请尝试以下操作。使用 的默认属性require
。它应该有图像 src。
const images = featuredNames.map((image) => {
const img = require(`../images/${image}.jpg`).default;
return (
<img
key={image}
src={img}
alt='Beer picture'
/>
);
});
推荐阅读
- python - 如何将包装字节转换为 Python Dataframe 中的实际字节?
- c# - “无法添加或更新子行:外键约束失败”错误
- python - 在网站中抓取关于我们的引用时没有结果
- r - 在 R 中,将“Oct 29 - Nov 1”转换为“20201029”和“20201101”
- r - 用因子的标准误差绘制系数点估计
- go - Google App Engine - 从应用程序代码中读取 JSON 文件
- python - 将 For 循环转换为函数 python 和函数参数说明
- python - 平滑折线图python中的曲线
- python - 在一个句子块中找到一起出现的单词(不一定是相邻的)。词是字典的关键词| Python
- python - 如何使用 Python 动态调用文件目录中的用户名