You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React Hooks如何通过子组件按钮点击将item.id传递给父组件?

Solution: Pass Item ID from Child to Parent Component

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 handleShowDetails function in App is passed to MyList as the onShowDetails prop. 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 onClick to call props.onShowDetails with the specific item.id—this ensures we send the correct ID for the clicked list item.
  • State Tracking (Optional): Using useState in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:22:56