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

如何获取Material UI DataGrid的数据并传递至下一个组件?

解决Material UI DataGrid获取表格数据的问题

问题原因

你创建了tableRef但没有将其绑定到DataGrid组件上,所以tableRef.current返回undefined。另外当前代码里的rows是静态常量,表格编辑后数据不会同步更新,直接传递原始rows会丢失编辑后的内容。

方案一:使用受控状态管理表格数据(推荐)

通过useState维护表格数据,编辑操作会自动更新状态,随时能获取最新数据:

import React, { useState } from "react";
import { DataGrid, GridRowsProp, GridColDef } from "@mui/x-data-grid";
import { Stack, Button } from "@mui/material";
import FolderIcon from "@mui/icons-material/Folder";
import KeyboardTabIcon from "@mui/icons-material/KeyboardTab";

const columnOptions = {
  editable: true,
  headerAlign: "center",
  width: 500,
  align: "center",
  disableColumnMenu: true,
  sortable: false,
};

const initialRows = [
  { id: 1, col1: "Kontreyler terminali", col2: 0, col3: 0 },
  { id: 2, col1: "Acer", col2: 10, col3: 10 },
  { id: 3, col1: "Microsoft", col2: 20, col3: 20 },
  { id: 4, col1: "Samsung", col2: 30, col3: 30 },
  { id: 5, col1: "Apple", col2: 40, col3: 40 },
];

const columns = [
  { field: "col1", headerName: "Hududlar", ...columnOptions },
  { field: "col2", headerName: "X koordinata", ...columnOptions },
  { field: "col3", headerName: "Y koordinata", ...columnOptions },
];

const Home = () => {
  const [rows, setRows] = useState<GridRowsProp>(initialRows);

  // 处理单元格编辑完成事件
  const handleCellEditCommit = (params) => {
    const updatedRows = rows.map(row => 
      row.id === params.id ? { ...row, [params.field]: params.value } : row
    );
    setRows(updatedRows);
  };

  // 获取当前表格数据
  const handleGetData = () => {
    console.log("当前表格数据:", rows);
    // 这里可以通过路由状态、上下文或props将rows传递给下一个组件
  };

  // 跳转到下一个组件并传递数据
  const handleNext = () => {
    // 示例:若使用react-router,可通过state传递数据
    // navigate('/next-page', { state: { tableData: rows } })
    console.log("传递给下一个组件的数据:", rows);
  };

  return (
    <div style={{ height: "92.5vh", width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        editMode="cell"
        autoHeight="true"
        density="comfortable"
        hideFooter="true"
        onCellEditCommit={handleCellEditCommit}
        sx={{ 
          fontSize: "20px", 
          "& .MuiDataGrid-cell:hover": { color: "primary.main" }, 
          fontFamily: "'Roboto', sans-serif", 
          fontWeight: 600 
        }}
      />
      <Stack
        direction={"row"}
        spacing={5}
        sx={{
          mt: "15px",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <Button 
          variant="contained" 
          size="large" 
          startIcon={<FolderIcon />}
          onClick={handleGetData}
        >
          Get Data
        </Button>
        <Button 
          variant="outlined" 
          size="large" 
          startIcon={<KeyboardTabIcon />}
          onClick={handleNext}
        >
          Next
        </Button>
      </Stack>
    </div>
  );
};

export default Home;

方案二:使用ref获取表格数据

如果一定要用ref,需要先将ref绑定到DataGrid,再通过DataGrid的API获取数据:

import React, { useRef, useEffect } from "react";
import { DataGrid, GridRowsProp, GridColDef } from "@mui/x-data-grid";
import { Stack, Button } from "@mui/material";
import FolderIcon from "@mui/icons-material/Folder";
import KeyboardTabIcon from "@mui/icons-material/KeyboardTab";

// 省略columnOptions、initialRows、columns定义,与方案一一致

const Home = () => {
  const tableRef = useRef<DataGrid>(null);

  // 组件挂载后打印ref
  useEffect(() => {
    console.log(tableRef.current); // 现在能获取到DataGrid实例
  }, []);

  const handleGetData = () => {
    if (tableRef.current) {
      // 通过API获取当前表格的所有行数据
      const currentRows = tableRef.current.getRows();
      console.log("当前表格数据:", currentRows);
    }
  };

  const handleNext = () => {
    if (tableRef.current) {
      const currentRows = tableRef.current.getRows();
      // 传递数据给下一个组件
      console.log("传递给下一个组件的数据:", currentRows);
    }
  };

  return (
    <div style={{ height: "92.5vh", width: "100%" }}>
      <DataGrid
        ref={tableRef} // 关键:绑定ref到DataGrid
        rows={initialRows}
        columns={columns}
        editMode="cell"
        autoHeight="true"
        density="comfortable"
        hideFooter="true"
        sx={{ 
          fontSize: "20px", 
          "& .MuiDataGrid-cell:hover": { color: "primary.main" }, 
          fontFamily: "'Roboto', sans-serif", 
          fontWeight: 600 
        }}
      />
      <Stack
        direction={"row"}
        spacing={5}
        sx={{
          mt: "15px",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <Button 
          variant="contained" 
          size="large" 
          startIcon={<FolderIcon />}
          onClick={handleGetData}
        >
          Get Data
        </Button>
        <Button 
          variant="outlined" 
          size="large" 
          startIcon={<KeyboardTabIcon />}
          onClick={handleNext}
        >
          Next
        </Button>
      </Stack>
    </div>
  );
};

export default Home;

关键说明

  • 受控状态方案符合React数据流理念,能实时跟踪数据变化,适合大多数场景。
  • ref方案依赖DataGrid内部API,需确保ref正确绑定,且API版本兼容(MUI X DataGrid的getRows()方法在v5+版本可用)。

内容的提问来源于stack exchange,提问作者83hru2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:15:28