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

Material UI V5中通过弹窗编辑表单更新DataGrid行的方法

Material UI DataGrid 弹窗编辑行实现方案

以下是基于Material UI V5.11社区版的具体实现步骤和代码示例:

核心思路

  1. 通过状态控制编辑弹窗的显示/隐藏,以及存储当前待编辑的行数据
  2. 在DataGrid的操作列中渲染编辑按钮,点击时将当前行数据传入状态并打开弹窗
  3. 弹窗内使用表单组件绑定待编辑数据,提交时更新DataGrid的数据源

完整代码示例

import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField } from '@mui/material';

// 初始数据源
const initialRows = [
  { id: 1, name: '张三', age: 28, email: 'zhangsan@example.com' },
  { id: 2, name: '李四', age: 32, email: 'lisi@example.com' },
  { id: 3, name: '王五', age: 25, email: 'wangwu@example.com' },
];

export default function EditRowWithDialog() {
  const [rows, setRows] = useState(initialRows);
  const [openDialog, setOpenDialog] = useState(false);
  const [editRow, setEditRow] = useState(null);

  // 列定义
  const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'name', headerName: '姓名', width: 130 },
    { field: 'age', headerName: '年龄', width: 90 },
    { field: 'email', headerName: '邮箱', width: 200 },
    {
      field: 'actions',
      headerName: '操作',
      width: 100,
      renderCell: (params) => (
        <Button 
          variant="contained" 
          size="small"
          color="primary"
          onClick={() => {
            // 存储当前行数据,打开弹窗
            setEditRow({...params.row});
            setOpenDialog(true);
          }}
        >
          编辑
        </Button>
      ),
    },
  ];

  // 保存编辑内容
  const handleSave = () => {
    if (!editRow) return;
    // 更新数据源,替换对应ID的行数据
    const updatedRows = rows.map(row => 
      row.id === editRow.id ? editRow : row
    );
    setRows(updatedRows);
    // 关闭弹窗,清空编辑状态
    setOpenDialog(false);
    setEditRow(null);
  };

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        disableRowSelectionOnClick
      />

      {/* 编辑弹窗 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
        <DialogTitle>编辑用户信息</DialogTitle>
        <DialogContent>
          <TextField
            margin="dense"
            label="姓名"
            value={editRow?.name || ''}
            onChange={(e) => setEditRow(prev => ({...prev, name: e.target.value}))}
            fullWidth
            required
          />
          <TextField
            margin="dense"
            label="年龄"
            type="number"
            value={editRow?.age || ''}
            onChange={(e) => setEditRow(prev => ({...prev, age: parseInt(e.target.value) || ''}))}
            fullWidth
            required
          />
          <TextField
            margin="dense"
            label="邮箱"
            type="email"
            value={editRow?.email || ''}
            onChange={(e) => setEditRow(prev => ({...prev, email: e.target.value}))}
            fullWidth
            required
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button onClick={handleSave} color="primary">保存</Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

关键说明

  • 在操作列的renderCell中,通过params.row获取当前行的完整数据,点击编辑按钮时将其存入editRow状态
  • 弹窗内的表单通过onChange实时更新editRow的字段值,确保数据双向绑定
  • 保存时通过map方法遍历数据源,替换对应ID的行数据,实现DataGrid的更新
  • 使用{...params.row}拷贝行数据,避免直接修改原数据源导致的状态异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:42:39