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

如何在MUI DataGrid中根据下拉选项同步修改对应行薪资单元格值

解决方案

要实现选择Experience下拉选项后同步显示对应索引的Salary,可通过状态管理与组件交互完成,具体步骤如下:

1. 新增状态跟踪选中索引

在组件中用useState存储每行选中的experience索引,初始默认选中第0项:

const [selectedIndices, setSelectedIndices] = useState(() => {
  return rows.reduce((acc, row) => {
    acc[row.id] = 0;
    return acc;
  }, {});
});

2. 修改Dropdown组件,添加交互逻辑

更新Dropdown组件,实现下拉选择时更新对应行的选中索引:

function Dropdown({ params, selectedIndex, onIndexChange }) {
  const handleChange = (e) => {
    const index = parseInt(e.target.value, 10);
    onIndexChange(params.row.id, index);
  };

  if (params.value && params.value.length > 0) {
    return (
      <select value={selectedIndex} onChange={handleChange}>
        {params.value.map((x, y) => (
          <option key={y} value={y}>{x}</option>
        ))}
      </select>
    );
  }
  return null;
}

3. 更新列配置关联状态

  • Experience列:传递选中索引和更新函数给Dropdown组件
  • Salary列:根据当前行的选中索引获取对应薪资值
const columns: GridColumns = [
  { field: "jobTitle", headerName: "Job Title", width: 200 },
  {
    field: "recruitmentDate",
    headerName: "Recruitment Date",
    type: "date",
    width: 150
  },
  {
    field: "experience",
    headerName: "Experience",
    renderCell: (params) => {
      return (
        <Dropdown 
          params={params} 
          selectedIndex={selectedIndices[params.row.id]} 
          onIndexChange={(rowId, index) => {
            setSelectedIndices(prev => ({ ...prev, [rowId]: index }));
          }} 
        />
      );
    }
  },
  {
    field: "salary",
    headerName: "Salary",
    valueGetter: (params) => {
      const salaryArr = params.row.salary as number[];
      const selectedIndex = selectedIndices[params.row.id];
      return salaryArr[selectedIndex];
    }
  }
];

逻辑说明

  • 初始状态下,每行默认选中experience数组第0项,Salary列同步显示对应索引的薪资
  • 用户切换下拉选项时,触发handleChange更新该行的选中索引
  • Salary列通过valueGetter实时读取最新选中索引对应的薪资值,实现联动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:23:31