乐闻世界logo
搜索文章和话题

How to pass data from child component to parent component in React?

1个答案

1

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)

jsx
import 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)

jsx
import 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:

  1. ParentComponent defines a state childData and a handler function handleDataFromChild. This function receives data from the child component and stores it in the childData state.
  2. ParentComponent passes the handleDataFromChild function as a prop (onData) to ChildComponent.
  3. In ChildComponent, a button triggers the sendDataToParent function, which calls the received onData prop and passes some data to the parent component.
  4. Once the data is passed to the parent component, it is stored in the childData state, 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 回复

你的答案