React循环中点击仅修改单个图片display状态的实现方法
Hey there! The issue you’re facing is that your current imgDisplay state is a single value shared across all photos—so when you update it, every image in the loop responds to that change, making all of them show up at once. Let’s adjust this to track visibility per individual photo instead.
Step 1: Refactor Your State Structure
Instead of a generic imgDisplay flag, store the ID of the photo you want to show (or an array if you want multiple photos visible at once). Initialize it to null so no photos are visible by default:
constructor(props) { super(props); this.state = { activePhotoId: null }; }
Step 2: Update the Click Handler
Modify handleShowPhoto to accept the photo’s ID as a parameter. This way, we know exactly which photo was clicked. We can also add logic to toggle the photo’s visibility if it’s already active:
handleShowPhoto = (photoId) => { this.setState(prevState => ({ // If the clicked photo is already active, hide it; otherwise, show it activePhotoId: prevState.activePhotoId === photoId ? null : photoId })); };
Step 3: Adjust the Render Logic
In your loop, check if the current photo’s ID matches the activePhotoId in state. Only show the image if they match:
<tr key={photo.id}> <td> {/* Pass the photo's ID to the handler when clicked */} <a href="#" onClick={() => this.handleShowPhoto(photo.id)}>{photo.title}</a> </td> <td> <img style={{ display: this.state.activePhotoId === photo.id ? 'block' : 'none' }} src={photo.thumbnailUrl} alt={photo.title} {/* Always add descriptive alt text for accessibility! */} /> </td> </tr>
Bonus: Allow Multiple Visible Photos
If you want users to show/hide multiple photos at once, switch to an array in state to track all active photo IDs:
Updated State:
this.state = { activePhotoIds: [] };
Updated Handler:
handleShowPhoto = (photoId) => { this.setState(prevState => ({ activePhotoIds: prevState.activePhotoIds.includes(photoId) ? // Remove the ID if it's already in the array (hide the photo) prevState.activePhotoIds.filter(id => id !== photoId) : // Add the ID if it's not present (show the photo) [...prevState.activePhotoIds, photoId] })); };
Updated Render:
<img style={{ display: this.state.activePhotoIds.includes(photo.id) ? 'block' : 'none' }} src={photo.thumbnailUrl} alt={photo.title} />
This approach ensures only the specific photo(s) you click are toggled, instead of updating every image in your loop.
内容的提问来源于stack exchange,提问作者Neil

