繁体   English   中英

使用 map function 将 onClick 传递给每个图像

[英]Pass onClick to each image using map function

我希望将 onClick function 传递给使用 map function 创建的每个图像元素。这样当用户单击缩略图时,它会将主图像更改为被单击的缩略图。

然而,现在似乎 onClick function 甚至没有被点击就被调用,显示的图像是数组中的最后一个图像。

此外,当我单击图像时,什么也没有发生。

我觉得可能存在多个问题,但不确定是什么。

let currentIndex = 0;

let changeImage = function(index) {
  currentIndex = index;
}

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}
          index={index}
          onclick={changeImage(index)}
        />
      ))}
    </Grid>
  ) : null;

上面的代码影响下面的代码。

<div>
 {console.log('index is: ' + currentIndex)}
 <GatsbyImage
   image={product.images[currentIndex].gatsbyImageData}
   alt={product.title}
 />
 {gallery}
</div>

将箭头 function 添加到这样的语法中,更改 onclick={changeImage(index)}

到这个 onclick={()=>changeImage(index)}

和重新渲染。

我认为您需要使用 state 而不是 let change let currentIndex = 0; const [currentIndex,setCurrentindex]=useState(0) and currentIndex = index; 对于 setCurrentindex(index) 我们使用 State 在发生变化时重新呈现 dom,在您的情况下,dom 没有重新呈现,因为您没有使用 state。这应该可以解决您的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM