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

MUI-X DataGrid社区版singleSelect编辑时空白报错求助

问题分析

你的singleSelect列配置中,getOptionValue指定了选项值为对象的numerical数字属性,但行数据里的test字段是完整对象。进入编辑状态时,编辑器接收的是整个对象而非对应数字,无法匹配选项列表中的值,因此下拉框空白并抛出范围错误。

解决方案

通过两个列配置属性处理数据转换:

  • preProcessEditCellProps:进入编辑前,将对象转换为对应的数字值,供编辑器使用
  • valueSetter:编辑完成后,将选中的数字值转换回对应对象,更新到行数据

修改后的列配置代码:

const columnsSetup = [
    {
        field: "test",
        headerName: "Object Dropdown",
        editable: true,
        type: "singleSelect",
        defaultValue: { short: "T2", numerical: 1 },
        valueOptions: [
            { short: "T2", numerical: 1 },
            { short: "T3", numerical: 2 },
            { short: "T4", numerical: 3 },
            { short: "T5", numerical: 4 },
            { short: "T6", numerical: 5 },
            { short: "T7", numerical: 6 },
            { short: "T8", numerical: 7 },
        ],
        valueFormatter: ({ value }) => {
            return value.short;
        },
        getOptionValue: (value) => value.numerical,
        getOptionLabel: (value) => value.short,
        sortComparator: (v1, v2) => {
            return gridNumberComparator(v1.numerical, v2.numerical);
        },
        // 编辑前转换值为数字
        preProcessEditCellProps: (props) => {
            return {
                ...props,
                value: props.value.numerical,
            };
        },
        // 编辑完成后转换数字回对象
        valueSetter: (params) => {
            const targetOption = params.colDef.valueOptions.find(opt => opt.numerical === params.value);
            if (targetOption) {
                params.row.test = targetOption;
                return true;
            }
            return false;
        }
    },
];

修改后,进入编辑模式时编辑器会拿到正确的数字值,下拉框正常显示选项;编辑保存后,行数据会保持原有的对象结构,显示不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:17:30