[英]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.