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

如何在MUI Data Grid中根据条件设置列不可编辑

MUI Data Grid 实现百分比与分数列互斥编辑

实现思路

核心是利用Data Grid列定义的editable属性(支持函数形式),结合行数据状态与编辑事件,动态控制对应列的可编辑权限:

  • 当percentage列已有值或正在编辑时,score列不可编辑
  • 当score列已有值或正在编辑时,percentage列不可编辑

完整代码示例

import { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';

export default function MutuallyExclusiveEditingGrid() {
  // 跟踪当前正在编辑的行与字段
  const [activeEdit, setActiveEdit] = useState(null);

  const handleEditStart = (params) => {
    if (['percentage', 'score'].includes(params.field)) {
      setActiveEdit({ rowId: params.id, field: params.field });
    }
  };

  const handleEditStop = () => {
    setActiveEdit(null);
  };

  const columns = [
    { field: 'id', headerName: 'ID', width: 90, editable: false },
    {
      field: 'percentage',
      headerName: '百分比',
      width: 150,
      editable: (params) => {
        // 若当前行的score已有值,或正在编辑score,则禁用percentage编辑
        return !(params.row.score || (activeEdit?.rowId === params.id && activeEdit?.field === 'score'));
      },
    },
    {
      field: 'score',
      headerName: '分数',
      width: 150,
      editable: (params) => {
        // 若当前行的percentage已有值,或正在编辑percentage,则禁用score编辑
        return !(params.row.percentage || (activeEdit?.rowId === params.id && activeEdit?.field === 'percentage'));
      },
    },
  ];

  const rows = [
    { id: 1, percentage: '', score: '' },
    { id: 2, percentage: '85%', score: '' },
    { id: 3, percentage: '', score: '92' },
  ];

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        onEditStart={handleEditStart}
        onEditStop={handleEditStop}
        editMode="cell" // 可根据需求改为"row"
      />
    </div>
  );
}

代码说明

  1. 编辑状态跟踪:通过activeEdit状态记录当前正在编辑的行ID和字段,确保编辑过程中另一列实时禁用
  2. 动态可编辑判断:editable函数结合行数据已有值和当前编辑状态,返回布尔值控制列的可编辑性
  3. 适配编辑模式:支持单元格编辑(cell)和行编辑(row)两种模式,根据业务需求切换

(图片说明:表格中展示了三行数据,第一行的百分比和分数列均为空,均可编辑;第二行已填写百分比,分数列呈灰化不可编辑状态;第三行已填写分数,百分比列呈灰化不可编辑状态)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:57:34