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

如何从ReactDataGrid子组件向父组件传递行ID?

ReactDataGrid行ID跨组件传递解决方案

核心思路

父组件维护选中行ID的状态,Table组件通过ReactDataGrid的行选择事件将ID传递给父组件,父组件再把ID传入CallPopUp组件用于API操作。

分步实现

1. 父组件CallForm:维护选中ID状态并传递回调

在父组件中添加状态存储选中的行ID,同时定义回调函数接收Table组件传来的ID,并将ID传递给CallPopUp。

import { useState } from 'react';
import Table from './Table';
import CallPopUp from './CallPopUp';

function CallForm() {
  const [selectedRowId, setSelectedRowId] = useState(null);

  const handleRowSelect = (rowId) => {
    setSelectedRowId(rowId);
  };

  return (
    <div>
      <Table onRowSelect={handleRowSelect} />
      <CallPopUp selectedId={selectedRowId} />
    </div>
  );
}

export default CallForm;

2. Table组件:配置ReactDataGrid实现行选择并传递ID

通过getRowId指定行的唯一标识字段,开启行选择功能,监听选择事件将选中行的ID通过回调传给父组件。

import ReactDataGrid from '@inovua/reactdatagrid-community';
import '@inovua/reactdatagrid-community/index.css';

function Table({ onRowSelect }) {
  const columns = [
    { name: 'id', header: 'ID', defaultWidth: 100 },
    // 其他业务列配置...
  ];

  // 指定行的唯一ID字段(根据你的数据源调整,比如row.id)
  const getRowId = (row) => row.id;

  // 处理单选选择事件
  const handleSelectionChange = ({ selectedRows }) => {
    if (selectedRows.length) {
      const selectedRow = selectedRows[0];
      onRowSelect(getRowId(selectedRow));
    } else {
      onRowSelect(null);
    }
  };

  return (
    <ReactDataGrid
      columns={columns}
      data={yourDataSource} // 替换为你的实际数据源数组
      getRowId={getRowId}
      enableRowSelect={true}
      selectionMode="single" // 单选模式,如需多选改为"multiple"
      onSelectionChange={handleSelectionChange}
    />
  );
}

export default Table;

3. CallPopUp组件:利用传入的ID进行API操作

接收父组件传递的selectedId,基于该ID发起GET/PUT/DELETE请求。

import { useEffect, useState } from 'react';

function CallPopUp({ selectedId }) {
  const [rowData, setRowData] = useState(null);

  // 获取选中行的详情数据
  useEffect(() => {
    if (!selectedId) return;

    const fetchRowData = async () => {
      try {
        const res = await fetch(`/api/your-resource/${selectedId}`);
        const data = await res.json();
        setRowData(data);
      } catch (err) {
        console.error('获取数据失败:', err);
      }
    };

    fetchRowData();
  }, [selectedId]);

  // 更新数据
  const handleUpdate = async () => {
    if (!selectedId || !rowData) return;

    try {
      await fetch(`/api/your-resource/${selectedId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(rowData),
      });
      alert('数据更新成功');
      // 可选:触发表格数据刷新
    } catch (err) {
      console.error('更新失败:', err);
    }
  };

  // 删除数据
  const handleDelete = async () => {
    if (!selectedId) return;

    if (window.confirm('确定要删除该行数据吗?')) {
      try {
        await fetch(`/api/your-resource/${selectedId}`, {
          method: 'DELETE',
        });
        alert('数据删除成功');
        // 可选:触发表格数据刷新并清空选中状态
      } catch (err) {
        console.error('删除失败:', err);
      }
    }
  };

  return (
    <div className="call-popup">
      {selectedId ? (
        <>
          <h4>选中行ID: {selectedId}</h4>
          {rowData && (
            <div className="row-details">
              <pre>{JSON.stringify(rowData, null, 2)}</pre>
            </div>
          )}
          <div className="popup-actions">
            <button onClick={handleUpdate}>更新</button>
            <button onClick={handleDelete} style={{ backgroundColor: '#dc3545', color: 'white' }}>删除</button>
          </div>
        </>
      ) : (
        <p>请先选择表格中的一行</p>
      )}
    </div>
  );
}

export default CallPopUp;

关键注意事项

  • getRowId的正确性:必须指定数据源中唯一的字段作为行ID(如row.id),不要使用数组索引,避免数据排序/更新后行标识混乱。
  • 多选场景适配:如果需要多选,将selectionMode改为"multiple",父组件状态改为数组const [selectedRowIds, setSelectedRowIds] = useState([]),Table组件的handleSelectionChange中传递selectedRows.map(row => getRowId(row))。
  • 事件替代方案:也可以使用onRowSelected事件替代onSelectionChange,适合监听单一行的选中/取消操作:
    const handleRowSelected = ({ row, isSelected }) => {
      onRowSelect(isSelected ? getRowId(row) : null);
    };
    
    然后在ReactDataGrid中添加onRowSelected={handleRowSelected}。

内容的提问来源于stack exchange,提问作者Ofir Kadosh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:57:46