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

React+MUI X Data Grid行编辑实现求助:点击图标开启指定单元格编辑

MUI X Data Grid 行内编辑实现方案

核心思路

通过维护editingRowId状态记录当前编辑的行ID,配合自定义单元格渲染逻辑,实现点击编辑图标后指定单元格切换为可编辑状态。

具体实现步骤

1. 状态定义

在组件中添加状态管理当前编辑行和表格数据:

const [editingRowId, setEditingRowId] = useState(null);
const [rowData, setRowData] = useState(/* 你的初始表格数据 */);

2. 操作列(含编辑图标)

新增操作列,渲染编辑按钮,点击时切换当前编辑行:

{
  field: 'actions',
  headerName: '操作',
  width: 120,
  renderCell: (params) => (
    <Box sx={{ display: 'flex', gap: 1 }}>
      <IconButton
        onClick={() => setEditingRowId(params.id === editingRowId ? null : params.id)}
      >
        <EditIcon />
      </IconButton>
      {/* 保留你已实现的删除按钮 */}
      <IconButton onClick={() => handleDelete(params.id)}>
        <DeleteIcon />
      </IconButton>
    </Box>
  ),
}

3. 自定义可编辑单元格

Document Type(下拉列表)

{
  field: 'documentType',
  headerName: 'Document Type',
  width: 200,
  renderCell: (params) => {
    if (params.id === editingRowId) {
      return (
        <Select
          value={params.value}
          onChange={(e) => {
            const updatedRows = rowData.map(row => 
              row.id === params.id ? {...row, documentType: e.target.value} : row
            );
            setRowData(updatedRows);
          }}
          fullWidth
        >
          <MenuItem value="Invoice">Invoice</MenuItem>
          <MenuItem value="Receipt">Receipt</MenuItem>
          <MenuItem value="Contract">Contract</MenuItem>
          {/* 根据你的需求添加更多选项 */}
        </Select>
      );
    }
    return params.value;
  },
}

Remark(文本输入框)

{
  field: 'remark',
  headerName: 'Remark',
  width: 300,
  renderCell: (params) => {
    if (params.id === editingRowId) {
      return (
        <TextField
          value={params.value}
          onChange={(e) => {
            const updatedRows = rowData.map(row => 
              row.id === params.id ? {...row, remark: e.target.value} : row
            );
            setRowData(updatedRows);
          }}
          fullWidth
          variant="standard"
        />
      );
    }
    return params.value;
  },
}

4. 可选:添加保存按钮

如果需要确认编辑后再提交,可在操作列切换显示保存按钮:

renderCell: (params) => (
  <Box sx={{ display: 'flex', gap: 1 }}>
    {params.id === editingRowId ? (
      <IconButton onClick={() => {
        setEditingRowId(null);
        // 这里可添加提交后端的API调用逻辑
      }}>
        <SaveIcon />
      </IconButton>
    ) : (
      <IconButton onClick={() => setEditingRowId(params.id)}>
        <EditIcon />
      </IconButton>
    )}
    <IconButton onClick={() => handleDelete(params.id)}>
      <DeleteIcon />
    </IconButton>
  </Box>
),

关键注意点

  • 确保你的行数据包含唯一id字段,Data Grid依赖此字段识别行
  • 更新数据时保持不可变性,用map生成新数组而非直接修改原数据
  • 若需持久化数据,在保存阶段调用后端接口提交更新后的数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:18