代码之家  ›  专栏  ›  技术社区  ›  krichey15

如何正确使用map函数获取数组中元素的索引?

  •  0
  • krichey15  · 技术社区  · 2 年前

    您好,我正在尝试使用map查找数组中元素的索引,以便最终创建一个onClick函数,该函数将根据该索引更改图像。

    然而,当我将索引添加到map函数时,我会得到一个错误,表明img没有定义。

    const currentIndex = 0;
    
    const gallery = 
      product.images.length > 1 ? (
        <Grid gap={2} columns={5}>
          {product.images.map(img, index => (
            <GatsbyImage 
              image={img.gatsbyImageData}
              key={img.id}
              alt={product.title}
            />
          ))}
        </Grid>
      ) : null; 
    

    上面的代码显示缩略图大小的图像列表。我希望每一张图片最终都能显示得更大。

    下面是大图的代码。

    <div>
      <GatsbyImage
        image={product.images[currentIndex].gatsbyImageData}
        alt={product.title}
      />
      {gallery}
    </div>
    
    2 回复  |  直到 2 年前
        1
  •  3
  •   Ian Rios    2 年前

    简单括号修复:

    const currentIndex = 0;
    
    const gallery = 
      product.images.length > 1 ? (
        <Grid gap={2} columns={5}>
          {product.images.map((img, index) => (
            <GatsbyImage 
              image={img.gatsbyImageData}
              key={img.id}
              alt={product.title}
            />
          ))}
        </Grid>
      ) : null; 
    

    确保不要将两个值传递给数组,而是将一个值传递给数组。map:一个具有自己的可选参数“index”的函数

    把你的工作扩展到一个你可以参考的功能,让生活更轻松,代码更清晰,像这样:

    const currentIndex = 0;
    
    const mapper = (img, index) => (
      <GatsbyImage image={img.gatsbyImageData} key={img.id} alt={product.title} />
    );
    
    const gallery =
      product.images.length > 1 ? (
        <Grid gap={2} columns={5}>
          {product.images.map(mapper)}
        </Grid>
      ) : null;
    

    更多信息请参见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#syntax