首页 > 解决方案 > 如何在 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}</>;
}

这将返回标题和描述,但图像未加载,仅显示替代文本。

我一直在尝试使用这些示例,但它总是导致出现替代文本。

标签: javascriptreactjs

解决方案


您可以将文件夹移动imagespublic文件夹吗?如果可以,下面的代码应该可以工作

<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'
    />
  );
});

推荐阅读