gpt4 book ai didi

javascript - 单击 ReactJS 检索图像的索引

转载 作者:行者123 更新时间:2023-12-02 22:40:43 25 4
gpt4 key购买 nike

我的 Web 应用程序中有一个画廊,是使用 'React-Photo-Gallery.' 导入的

我可以用图像填充图库,然后单击即可打开照片轮播。如何检索使用 onClick 方法单击的图像的索引? activeIndex 默认设置为 0,因此单击任何图像时,都会显示数组中的第一个图像。我希望单击的图像显示在轮播/灯箱中。

const mappingFunction = (img, index) => ({index, src: img.url, sizes: ["(min-width: 480px) 20vw,(min-width: 1024px) 25vw,25vw"], width: 4, height: 3});

const photosForGallery = images.map(mappingFunction)

映射图像后,我将其显示如下:

<Gallery photos={photosForGallery} direction={"column"} columns={4} onClick={() => this.setState({ activeIndex: *use index here*, isOpen: true })} />

{isOpen && (
<Lightbox
mainSrc={urls[activeIndex]}
mainSrcThumbnail={urls[activeIndex]}
nextSrc={urls[(activeIndex + 1) % urls.length]}
nextSrcThumbnail={urls[(activeIndex + 1) % urls.length]}
prevSrc={urls[(activeIndex + urls.length - 1) % urls.length]}
prevSrcThumbnail={urls[(activeIndex + urls.length - 1) % urls.length]}
onCloseRequest={() => this.setState({ isOpen: false })}
onMovePrevRequest={() =>
this.setState({
activeIndex: (activeIndex + urls.length - 1) % urls.length
})
}
onMoveNextRequest={() =>
this.setState({
activeIndex: (activeIndex + 1) % urls.length
})
}
/>
)}

我遇到困难的是访问所选图像的索引。我尝试过使用“this”关键字,甚至尝试实现回调函数。但是(如果我错了,请纠正我),单击时所选的元素似乎是图库本身,而不是我选择的图像。任何输入将不胜感激,因为我是 React/JS 的新手。

随着我进行更多研究,我将继续更新我的问题,但欢迎任何意见。

最佳答案

对于组件Gallery onClick 函数:

Optional. Do something when the user clicks a photo. Receives arguments event and an object containing the index, Photos obj originally sent and the next and previous photos in the gallery if they exist

http://neptunian.github.io/react-photo-gallery/api.html

因此,为了获取索引,您可能需要做的就是如下:

<Gallery
photos={photosForGallery}
direction={"column"}
columns={4}
onClick={(e, { index }) => this.setState({ activeIndex: index, isOpen: true })} /> // <---- HERE

关于javascript - 单击 ReactJS 检索图像的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com