首页 > 解决方案 > 在 Next.js 中渲染卡片组

问题描述

我试图弄清楚如何创建一个在 next.js 中呈现一组卡片的函数(使用反应语义 ui)。我的意思是,我有 50 张照片,我想创建而无需手动输入所有 50 张卡片,这是一个为我生成该组的功能。为此,我只需要一个索引,因为我的意图是作为图像 "/src/image/"+index+"/.png" 的 src 传递

我对语义 ui 和 next.js 不是很熟悉,但我可以做一些事情。我把我写的代码留给你,即使我认为有更快、更漂亮的解决方案,它仍然有效……唯一的问题是返回的第一个索引是最大值,即 50,然后是 1……为什么?

renderCard() {
    const index = [50];
    let i;
    for(i = 1; i<49;i++) index[i]=i
    const items = index.map(index => {
        return {
            image: "/src/image/"+index+".png",
            header: i
        };
    }); 
    return <Card.Group itemsPerRow={3} items={items}/>
}

标签: javascriptarraysloops

解决方案


内联评论。

renderCard() {
    const index = [50]; //This creates an array of one element
    // index[0] === 50

    let i;
    for(i = 1; i<49;i++) { //array indexes start at 0, not 1
        index[i]=i  //This adds numbers 1-49 to the end of array
    }
    //after this loop,
    //index === [50,1,2,...,48]

尝试此处列出的解决方案之一来初始化您的阵列。

例如

const index = Array.from(Array(50).keys());
//index === [0,1,2,...,49];

推荐阅读