如何从循环中使用下一张图片加载多张图片?

How can I load multiple images with Next Image from a loop?

我有:


const TEMPLATE_TYPES = [
    {
        name: 'Blog Post',
        type: 'blog-post',
        img: '/img1.png'
    },...
];

稍后,我循环了 TEMPLATE_TYPES:

{templateType.img && <img src={templateType.img} />}

但我想将其转换为 Next.js 的 <Image /> 标签。我将如何做到这一点?

谢谢!

来自 nextJs 文档:

Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

只要您的图像在 public 文件夹中,您就不必导入它们,所以保持原样即可。

// TEMPLATE_TYPES
img: '/img1.png'

但请记住:

Note: Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.

有关详细信息,请参阅 the docs about serving static content

另一件事,将来您可能想要从远程域访问文件,例如 aws 存储桶,在这种情况下,您必须像这样在 next.config.js 上添加域:

// next.config.js file
module.exports = {
  images: {
    domains: ['example.com', 'example2.com'],
  },
}

了解更多信息take a look here

最后,您可以创建一个获取对象并渲染图像的组件:

const RenderImage = (props) => {
  const images = props.images;
  return (
    <>
      {images.map((img, i) => (
        <div key={i}>
          <h4>{img.name}</h4>
          <Image src={img.img} width={500} height={300} />
        </div>
      ))}
    </>
  );
};

//Later somewhere on your code:
<RenderImage images={TEMPLATE_TYPES} />

上面的代码只是一个示例,但我想您明白了,另请参阅 the api docs 关于图像组件。希望我有所帮助!