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

如何基于rowData实现AG Grid中可编辑下拉列表的动态渲染?

解决方案

要实现每行下拉框选项对应当前行的cities数组,你不需要依赖Grid API或者复杂的状态修改,AG Grid的cellEditorParams支持通过函数动态生成参数,直接获取当前行数据即可。

关键修改点

  1. 修正参数拼写:agSelectCellEditor的选项配置是values(小写v),不是你代码里的Values
  2. 动态生成编辑器参数:将cellEditorParams设为函数,接收params参数,其中params.data就是当前行的完整数据,直接取params.data.cities作为下拉选项
  3. 完善值的读写逻辑:通过valueGetter控制单元格显示内容,valueSetter将选中值同步到行数据(建议新增字段存储选中值,避免修改原cities数组)

完整代码

export const AGTable = ({ rowData }) => {
    const defaultColDef = useMemo(() => ({
        sortable: true,
    }), []);

    const columnDefs = [
        { field: 'date', filter: true },
        { field: 'state' },
        {
            headerName: 'Cities',
            editable: true,
            cellEditor: 'agSelectCellEditor',
            // 动态生成下拉选项
            cellEditorParams: (params) => ({
                values: params.data.cities,
                valueListGap: 0
            }),
            // 控制单元格显示的内容:优先显示选中值,默认显示第一个城市
            valueGetter: (params) => params.data.selectedCity || params.data.cities[0],
            // 将选中的值保存到行数据的selectedCity字段
            valueSetter: (params) => {
                params.data.selectedCity = params.newValue;
                return true;
            }
        }
    ];

    return (
        <div className="ag-theme-alpine" style={{ width: "auto", height: 500 }}>
            <AgGridReact
                rowData={rowData}
                columnDefs={columnDefs}
                defaultColDef={defaultColDef}
            />
        </div>
    );
};

说明

  • 新增selectedCity字段存储用户选中的城市,避免修改原cities数组(如果你的业务逻辑需要直接修改cities,可以调整valueSetter的逻辑)
  • cellEditorParams的函数会在每次单元格进入编辑状态时执行,确保获取到当前行的最新数据
  • 不需要使用gridRef提前获取API,AG Grid会自动传递当前行的参数给编辑器配置函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:05:55