如何将Circle子组件的鼠标坐标状态传递给Main父组件?
Hey there! Let's work through this together—passing data from a child component up to its parent is a super common React pattern, and it’s totally doable with a callback function. Here’s exactly how to implement it for your use case:
Step 1: Set Up State and a Callback in the Parent (Main) Component
First, the parent component needs to hold the coordinate state and provide a function that the child can call to update that state.
import { useState } from 'react'; import Circle from './Circle'; function Main() { // Initialize state to store the mouse coordinates const [circleMouseCoords, setCircleMouseCoords] = useState({ x: 0, y: 0 }); // This callback will receive coordinates from the Circle component const handleCoordUpdate = (newCoords) => { setCircleMouseCoords(newCoords); // You can add any extra logic here—like logging or further calculations console.log('Received coords from Circle:', newCoords); }; return ( <div className="main-component"> {/* Pass the callback to the Circle component as a prop */} <Circle onUpdateCoords={handleCoordUpdate} /> {/* Now you can use the coordinates in the parent component! */} <div className="coords-display"> Mouse position in Circle: X={circleMouseCoords.x}, Y={circleMouseCoords.y} </div> </div> ); } export default Main;
Step 2: Modify the Child (Circle) Component to Use the Callback
In your Circle component, you’ll receive the callback prop and call it inside your UpdateCoords function to send the coordinates up to the parent.
function Circle({ onUpdateCoords }) { const UpdateCoords = (event) => { // Calculate the mouse position relative to the Circle div const elementRect = event.target.getBoundingClientRect(); const relativeX = event.clientX - elementRect.left; const relativeY = event.clientY - elementRect.top; // Call the parent's callback function with the new coordinates onUpdateCoords({ x: relativeX, y: relativeY }); }; return ( <div className="circle-element" onMouseMove={UpdateCoords} style={{ width: '250px', height: '250px', borderRadius: '50%', backgroundColor: 'coral', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'crosshair' }} > Move your mouse over this circle! </div> ); } export default Circle;
Key Concepts Explained
- React’s Unidirectional Data Flow: React only lets data flow down from parent to child via props. To send data up, we use a callback function (passed down as a prop) that the child can trigger with the data.
- Callback Prop: The parent defines
handleCoordUpdateand passes it to the child asonUpdateCoords. When the child callsonUpdateCoords(newCoords), it’s essentially telling the parent “here’s the new data—do what you need with it.” - Relative Coordinates: The calculation using
getBoundingClientRect()ensures we get the mouse position relative to the Circle div itself, not the entire window.
That’s it! Now whenever the user moves their mouse over the Circle component, the coordinates will be sent up to the Main component and stored in its state, ready for you to use however you need.
内容的提问来源于stack exchange,提问作者Deepak Kamat

