gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:26:07 26 4
gpt4 key购买 nike

我有:


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 (/).

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

// 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关于图像组件。希望我有所帮助!

关于javascript - 如何从循环中使用下一张图片加载多张图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71833147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com