使用React Hooks如何通过子组件按钮点击将item.id传递给父组件?
To make this work, we’ll use React’s standard parent-child prop communication pattern. The parent will pass a callback function to the child, and the child will trigger this function with the clicked item’s ID when the button is pressed. Here’s the step-by-step implementation:
Step 1: Update the Parent Component (App.js)
First, we’ll add a callback function in the parent to handle the ID sent from the child. We can also use useState to track the selected ID (optional but useful for demonstrating the flow):
import React, { useState } from 'react' import MyList from '../MyList' const App = props => { // Optional: Track the selected item ID in state const [selectedItemId, setSelectedItemId] = useState(null); // Callback function to receive the ID from the child const handleShowDetails = (itemId) => { setSelectedItemId(itemId); // Update state with the clicked ID console.log('Clicked item ID:', itemId); // Example: Log the ID for testing // Add your custom logic here (e.g., fetch item details, navigate to a detail page) }; return ( <div className='App'> {/* Pass the callback as a prop to MyList */} <MyList onShowDetails={handleShowDetails} /> {/* Optional: Display the selected ID to the user */} {selectedItemId && ( <p className='selected-id'>Selected Item ID: {selectedItemId}</p> )} </div> ) } export default App
Step 2: Update the Child Component (MyList.js)
Next, we’ll modify each "More details" button to call the parent’s callback function with the corresponding item’s ID:
import React from 'react' import jsonResponse from '../data' function MyList (props) { const list = jsonResponse.map((item) => { return ( <li className='list-container' key={item.id}> <h4>Name: {item.name}</h4> {/* Trigger the parent's callback with the current item's ID */} <button className='btn' onClick={() => props.onShowDetails(item.id)} > More details </button> </li> ) }) return ( <ul id='container'> {list} </ul> ) } export default MyList
Key Notes:
- Parent Callback: The
handleShowDetailsfunction inAppis passed toMyListas theonShowDetailsprop. This function accepts the item ID as an argument and can be used to trigger any parent-side logic. - Child Button Click: Each button uses an arrow function in
onClickto callprops.onShowDetailswith the specificitem.id—this ensures we send the correct ID for the clicked list item. - State Tracking (Optional): Using
useStatein the parent lets you store and display the selected ID, which is helpful if you need to use it for further actions like fetching detailed data for the item.
This approach follows React’s one-way data flow and is the standard method for passing data up from a child to a parent component.
内容的提问来源于stack exchange,提问作者user1941537

