In React, passing data from child components to parent components is typically achieved through callback functions. The parent component passes a callback function as a prop to the child component, and the child component calls this callback function to pass data back to the parent component.
Here's a simple example illustrating this process:
Assume we have a parent component ParentComponent and a child component ChildComponent.
Parent Component (ParentComponent)
jsximport React, { useState } from 'react'; import ChildComponent from './ChildComponent'; function ParentComponent() { const [childData, setChildData] = useState(''); const handleDataFromChild = (data) => { setChildData(data); console.log('Received data from child:', data); }; return ( <div> <h1>Parent Component</h1> <ChildComponent onData={handleDataFromChild} /> <p>Data from Child: {childData}</p> </div> ); } export default ParentComponent;
Child Component (ChildComponent)
jsximport React from 'react'; function ChildComponent({ onData }) { const sendDataToParent = () => { // Simulate some data const data = 'Hello from Child'; onData(data); }; return ( <div> <h1>Child Component</h1> <button onClick={sendDataToParent}>Send Data to Parent</button> </div> ); } export default ChildComponent;
In this example:
ParentComponentdefines a statechildDataand a handler functionhandleDataFromChild. This function receives data from the child component and stores it in thechildDatastate.ParentComponentpasses thehandleDataFromChildfunction as a prop (onData) toChildComponent.- In
ChildComponent, a button triggers thesendDataToParentfunction, which calls the receivedonDataprop and passes some data to the parent component. - Once the data is passed to the parent component, it is stored in the
childDatastate, and the parent component can use this data for further processing or display.
Using this pattern, we can flexibly pass data between components without disrupting React's data flow (which always flows from parent to child components). This approach helps maintain component independence and reusability.
2024年6月29日 12:07 回复