使用 map 函数将 onClick 传递给每个图像
Pass onClick to each image using map function
我希望将 onClick 函数传递给使用地图函数创建的每个图像元素。因此,当用户单击缩略图时,它会将主图像更改为被单击的缩略图。
但是现在似乎正在调用 onClick 函数,甚至没有被点击,显示的图像是数组中的最后一个图像。
同样,当我点击图片时没有任何反应。
我觉得可能存在多个问题,但不确定是什么。
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>
将箭头函数添加到这样的语法中,
更改 onclick={changeImage(index)}
到这个onclick={()=>changeImage(index)}
以及重新渲染。
我认为你需要使用 state 而不是 let
改变让 currentIndex = 0;
到
常量 [currentIndex,setCurrentindex]=useState(0)
和 currentIndex = 索引;
设置当前索引(索引)
我们使用 State 来重新渲染 dom 每当有变化时,在你的情况下 dom 没有重新渲染,因为你没有使用 state 。
那应该可以解决您的问题
我希望将 onClick 函数传递给使用地图函数创建的每个图像元素。因此,当用户单击缩略图时,它会将主图像更改为被单击的缩略图。
但是现在似乎正在调用 onClick 函数,甚至没有被点击,显示的图像是数组中的最后一个图像。
同样,当我点击图片时没有任何反应。
我觉得可能存在多个问题,但不确定是什么。
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>
将箭头函数添加到这样的语法中, 更改 onclick={changeImage(index)}
到这个onclick={()=>changeImage(index)}
以及重新渲染。
我认为你需要使用 state 而不是 let 改变让 currentIndex = 0; 到 常量 [currentIndex,setCurrentindex]=useState(0) 和 currentIndex = 索引; 设置当前索引(索引) 我们使用 State 来重新渲染 dom 每当有变化时,在你的情况下 dom 没有重新渲染,因为你没有使用 state 。 那应该可以解决您的问题