如何获取photo-container容器内被点击图片元素的索引?
.photo-container Got it, let's walk through how to grab the index of the clicked image inside your .photo-container component. I'll share two practical approaches that fit different use cases:
Approach 1: Find Index Using Container's Children
If you want to keep your current JSX structure (hardcoded <img> tags), you can use the event's currentTarget (which refers to the .photo-container element the click event is bound to) to get all image children, then calculate the index:
photoGallery(event) { // Get the container element that the onClick is attached to const photoContainer = event.currentTarget; // Convert the container's img children into an array const allImages = Array.from(photoContainer.querySelectorAll('img')); // Find the index of the clicked image const imageIndex = allImages.indexOf(event.target); console.log('Clicked image index:', imageIndex); this.setState({ imgSrc: event.target.src }); }
Pro Tip: Handle Edge Cases
If your images ever have nested elements (like captions), event.target might not be the <img> itself. To fix this, use closest() to ensure you're targeting the image element:
const clickedImg = event.target.closest('img'); const imageIndex = allImages.indexOf(clickedImg);
Approach 2: Pass Index Directly During Render (React-Friendly)
For a more scalable, React-native approach, store your image data in a state/array and render them with map(). This lets you pass the index directly to the click handler without extra DOM queries:
class PhotoGalleryComponent extends React.Component { constructor(props) { super(props); this.state = { imgSrc: '', // Store your image data in an array galleryImages: [ { src: 'https://img1.jpg', alt: 'img-1' }, { src: 'https://img2.jpg', alt: 'img-2' }, { src: 'https://img3.jpg', alt: 'img-3' } ] }; } // Handler receives the index directly photoGallery = (imageIndex, event) => { console.log('Clicked image index:', imageIndex); this.setState({ imgSrc: event.target.src }); } render() { return ( <div className="photo-container"> {this.state.galleryImages.map((image, index) => ( <img key={index} // Use a unique ID instead if you have one for better performance src={image.src} alt={image.alt} onClick={(e) => this.photoGallery(index, e)} /> ))} </div> ); } }
This method is cleaner if you plan to add/remove images dynamically later, since you won't have to adjust DOM query logic.
内容的提问来源于stack exchange,提问作者peronja

