ReactJS中鼠标悬停图片时如何打印当前图片索引
Got it, let's break down what's going wrong with your current code and fix it step by step:
1. The First Critical Issue: Incorrect Event Handler Binding
Right now you have:
onMouseOver={handleEvent()}
This immediately calls handleEvent when the component renders, not when the mouse hovers over the element. You need to pass the function reference instead:
onMouseOver={handleEvent}
2. You're Missing the Index Prop in Your Child Component
Your SolutionsSectionBoxItem only receives individual image, heading, etc., but it has no way to know its own position in the parent's list of items. Here's how to fix this:
Step 1: Pass the Index from the Parent
When you render SolutionsSectionBoxItem in the parent component (assuming you're using map to loop through a list of solutions), pass the index as a prop:
// Parent component example {solutionsList.map((solution, index) => ( <SolutionsSectionBoxItem key={index} index={index} // Pass the item's index here heading={solution.heading} image={solution.image} description={solution.description} solutionLink={solution.solutionLink} /> ))}
Step 2: Update the Child Component to Use the Index Prop
Modify your child component to accept the index prop, then use it in your hover handler to update state and log/alert the value:
import { useState } from 'react'; import { Link } from 'react-router-dom'; import styles from './your-styles.module.css'; function SolutionsSectionBoxItem({ heading, image, description, solutionLink, index // Add index to your props }) { const [bgImgIndex, setBgImgIndex] = useState(0); function handleEvent() { // Update state with the hovered item's index setBgImgIndex(index); // Log and alert the index as requested console.log('Hovered image index:', index); alert(`Hovered image index: ${index}`); } return ( <div className={styles["solutions-section-item-box"]} onMouseOver={handleEvent} > <Link to={solutionLink}> <div className={styles["solutions-section-item-title"]}>{heading}</div> <img src={image} alt={description} className={styles["solutions-section-item-img"]} /> </Link> </div> ); } export default SolutionsSectionBoxItem;
Why Your Original Code Failed
handleEvent()inonMouseOverruns immediately on component render, not when the hover event fires.bgImgIndexis a single number state (not an array), sobgImgIndex.indexOf(image)doesn't make sense—you can't callindexOfon a number. Even if it were an array, the child component doesn't have access to the full list of images to find the index from.
This approach will correctly capture the index of the hovered item, update your state, and log/alert the value as you need.
内容的提问来源于stack exchange,提问作者Vardan Hambardzumyan

