如何在react-native-image-viewer中下滑图片并获取数组内图片的URL/索引?
Hey there! I’ve worked with this component before, so let me break down exactly how to capture and log the current image’s index or URL when swiping through your gallery.
Core Idea
The react-native-image-viewer component comes with a built-in onChange prop that triggers every time the active image changes (this includes when you swipe left/right to navigate between images). This callback gives you direct access to the current image’s index, which you can use to fetch its corresponding URL from your image array.
Step-by-Step Implementation
Set up your image array
Make sure your image data follows the component’s required format: each item should be an object with aurlfield. For example:const imageList = [ { url: 'https://your-domain.com/image-1.png' }, { url: 'https://your-domain.com/image-2.png' }, { url: 'https://your-domain.com/image-3.png' }, ];Add the
onChangecallback
Define a function that accepts thecurrentIndexparameter, then use that index to get the matching image from your array and log the details. Here’s a complete component example:import React from 'react'; import ImageViewer from 'react-native-image-viewer'; const ImageGallery = () => { const imageList = [ { url: 'https://your-domain.com/image-1.png' }, { url: 'https://your-domain.com/image-2.png' }, { url: 'https://your-domain.com/image-3.png' }, ]; const handleImageSwitch = (currentIndex) => { // Get the current image object using the index const activeImage = imageList[currentIndex]; // Log the index and URL to console console.log('Current Image Index:', currentIndex); console.log('Current Image URL:', activeImage.url); }; return ( <ImageViewer imageUrls={imageList} onChange={handleImageSwitch} // Add other necessary props like `visible` (to control visibility) or `onClose` visible={true} // Adjust this based on your state management /> ); }; export default ImageGallery;Test it out
When you swipe between images in the viewer, thehandleImageSwitchfunction will fire instantly, and you’ll see the index and URL printed in your console.
Notes
- If you need to trigger the log only on a specific swipe direction, you could add extra logic to compare the previous index with the current one, but the basic
onChangeprop covers most use cases. - Double-check that your
imageListarray is correctly mapped to theimageUrlsprop of the component—this is a common gotcha!
内容的提问来源于stack exchange,提问作者Đặng Chí Sách

