简体   繁体   English

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

[英]Pass onClick to each image using map function

I am looking to pass an onClick function to each image element created using the map function. So that when a user clicks the thumbnail image it changes the main image to the thumbnail that was clicked.我希望将 onClick function 传递给使用 map function 创建的每个图像元素。这样当用户单击缩略图时,它会将主图像更改为被单击的缩略图。

Right now however it seems like the onClick function is being called without even being clicked and the image that is displayed is the last image in the array.然而,现在似乎 onClick function 甚至没有被点击就被调用,显示的图像是数组中的最后一个图像。

Also when I click the images nothing happens.此外,当我单击图像时,什么也没有发生。

I feel like there may be multiple issues but not sure what.我觉得可能存在多个问题,但不确定是什么。

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;

The above code is affecting the below code.上面的代码影响下面的代码。

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

add the arrow function to the syntax like this, change onclick={changeImage(index)}将箭头 function 添加到这样的语法中,更改 onclick={changeImage(index)}

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

and for the rerendering.和重新渲染。

i think you need to use state instead of let change let currentIndex = 0;我认为您需要使用 state 而不是 let change let currentIndex = 0; to const [currentIndex,setCurrentindex]=useState(0) and currentIndex = index; const [currentIndex,setCurrentindex]=useState(0) and currentIndex = index; to setCurrentindex(index) we use State to rerender the dom whenever there is a change, in your case the dom is not rerendering because you are not using state. that should solve your problem对于 setCurrentindex(index) 我们使用 State 在发生变化时重新呈现 dom,在您的情况下,dom 没有重新呈现,因为您没有使用 state。这应该可以解决您的问题

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

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