【发布时间】:2020-07-22 00:24:44
【问题描述】:
我有一个包含指向本地图像链接的数组的数据文件。当我尝试映射此数组并渲染图像列表时,方法 require() 允许我仅将图像文件的名称放入内部并单独访问路径,如下面代码的 image1 所示。
即使图像源看起来与 image1 示例中的相同,Image2 和 image3 也无法工作。
为什么会这样?我可以以某种方式解决它吗? 我不想在每次需要渲染图像列表时更正我的 src 属性。此外,通过导入获取图像并不是最好的方法,因为数组的长度可能很大,而且还可以动态变化。
感谢您的帮助和问候。
// news.image = 'news-img1.jpg',
// news.imageSrc = '../images/news-img1.jpg'
const NewsList = ({ newsList }) => {
const listItems = newsList.map((news) => {
return (
<li key={news.id}>
<img src={require(`../images/${news.image}`)} alt={news.title} /> // image1
<img src={require(`${news.imageSrc}`)} alt={news.titleSrc} /> // image2
<img src={require(news.imageSrc)} alt={news.titleSrc} /> // image3
</li>
)
})
return (
<section className="news-list">
<ul>
{listItems}
</ul>
</section>
);
}
export default NewsList;
【问题讨论】:
-
是否可以将实际 URL 作为 imageSrc 发送?目前,如果您正在为实际的网站/应用程序这样做,这种动态导入图像的方法绝对不是理想的方法。
标签: arrays reactjs image mapping require