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

MaterialTable:点击编辑按钮后如何让指定单元格显示下拉菜单?

解决方法

要实现仅在编辑行时显示下拉菜单,同时保留筛选栏的文本输入,你需要移除列配置中的lookup属性,改用editComponent自定义编辑时的输入组件。这样就能避免lookup同时影响筛选栏的问题。

修改后的代码示例

首先确保你导入了Material-UI的Select和MenuItem组件:

import { Select, MenuItem } from '@mui/material';

然后更新你的列配置和表格组件:

const agentOptions = { 34: "AGENT X", 63: "AGENT Y" };
const locationOptions = { 34: "İstanbul", 63: "Şanlıurfa" };

const columns = [
  {
    title: "Task ID",
    field: "taskId",
    editable: "never",
    filtering: true,
    queryParam: "taskId",
  },
  {
    title: "Shipment",
    field: "shipment",
    editable: "never",
    filtering: true,
    queryParam: "shipment",
  },
  {
    title: "Assigned Agent",
    field: "assignedAgent",
    filtering: true,
    queryParam: "assigned_agent",
    // 移除lookup,改用editComponent自定义编辑组件
    editComponent: (props) => (
      <Select
        value={props.value || ''}
        onChange={(e) => props.onChange(e.target.value)}
        fullWidth
      >
        {Object.entries(agentOptions).map(([id, name]) => (
          <MenuItem key={id} value={parseInt(id)}>
            {name}
          </MenuItem>
        ))}
      </Select>
    ),
    // 自定义表格显示文本,将存储的ID转换为对应名称
    render: (rowData) => agentOptions[rowData.assignedAgent] || rowData.assignedAgent
  },
  {
    title: "Put Away Location",
    field: "location",
    filtering: true,
    queryParam: "location",
    editComponent: (props) => (
      <Select
        value={props.value || ''}
        onChange={(e) => props.onChange(e.target.value)}
        fullWidth
      >
        {Object.entries(locationOptions).map(([id, name]) => (
          <MenuItem key={id} value={parseInt(id)}>
            {name}
          </MenuItem>
        ))}
      </Select>
    ),
    // 自定义表格显示文本,将存储的ID转换为对应名称
    render: (rowData) => locationOptions[rowData.location] || rowData.location
  },
];

<MaterialTable
  columns={columns}
  data={data}
  onRowClick={(event, rowData) => {
    history.push(`/return-to-seller-tasks/${rowData?.taskId}`, {
      taskId: rowData?.taskId,
    });
  }}
  editable={{
    onRowUpdate: (newData, oldData) =>
      new Promise((resolve, reject) => {
        setTimeout(() => {
          const dataUpdate = [...data];
          const index = oldData.tableData.id;
          dataUpdate[index] = newData;
          // setData([...dataUpdate]);
          resolve();
        }, 1000);
      }),
  }}
/>

关键说明

  1. 移除lookup:彻底避免它自动给筛选栏生成下拉菜单
  2. 自定义editComponent:用Material-UI的Select组件实现编辑时的下拉选择,完全控制编辑态的输入形式
  3. render属性:如果数据存储的是ID(如34、63),通过render把ID转换成对应名称,保证表格正常展示文本
  4. 筛选栏保留默认行为:未设置lookup时,筛选栏会保持默认的文本输入框,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:15:37