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

点击按钮修改Material UI DataGrid表格数据及获取点击行索引方法

解决方法

1. 获取行索引的核心方法

renderCell 回调返回的 params 对象已经包含了你需要的所有行信息,不需要手动遍历列获取数据:

  • 直接调用 params.api.getRowIndex(params.id) 即可获取当前点击行的索引
  • 直接取 params.row 即可获取当前行的完整数据,无需手动拼接

2. 修改指定行数据的实现逻辑

你当前代码中定义的 starWarsData 状态没有和传入的 data props 关联,且 DataGrid 绑定的是不可变的 props 数据,修改数据前需要先做状态同步:

  • 用 useEffect 监听传入的 data,同步更新到内部的 starWarsData 状态
  • DataGrid 的 rows 属性绑定内部状态 starWarsData
  • 点击按钮时,根据行索引修改状态数组中对应位置的指定字段即可

3. 修改后的完整代码

import Button from "@mui/material/Button";
import { DataGrid } from "@mui/x-data-grid";
import { useState, useEffect } from 'react';

function StarWarsTable({ data }) {
    // 同步props数据到内部状态,用于后续修改
    const [starWarsData, setStarWarsData] = useState([]);
    useEffect(() => {
        setStarWarsData(data);
    }, [data]);

    const columns = [
        {
            field: "action",
            headerName: "Action",
            sortable: false,
            width: 130,
            renderCell: (params) => {
                const onClick = (e) => {
                    e.stopPropagation(); 
                    // 1. 获取当前行索引
                    const rowIndex = params.api.getRowIndex(params.id);
                    console.log('当前点击行索引:', rowIndex);
                    // 2. 获取当前行完整数据
                    const currentRow = params.row;
                    console.log('当前行数据:', currentRow);

                    // 示例:修改当前行的favorite字段为true
                    setStarWarsData(prev => {
                        const newData = [...prev];
                        newData[rowIndex] = {
                            ...newData[rowIndex],
                            favorite: true
                        };
                        return newData;
                    })
                };
                return <Button onClick={onClick}>设为收藏</Button>;
            },
        },
        { field: "id", headerName: "ID", width: 130 },
        { field: "name", headerName: "Name", width: 130 },
        { field: "birthYear", headerName: "Birth Year", width: 130 },
        { field: "gender", headerName: "Gender", width: 130 },
        { field: "homeworld", headerName: "Home world", width: 130 },
        { field: "species", headerName: "Species", width: 130 },
        { field: "favorite", headerName: "Is Favorite", width: 130 },
    ];
    return (
        <div style={{ marginLeft: '10%', height: 400, width: "75%" }}>
            {/* 绑定内部可变状态 */}
            <DataGrid rows={starWarsData} columns={columns} pageSize={5} rowsPerPageOptions={[10]} />
        </div>
    );
}

export default StarWarsTable;

注意事项

如果你的表格开启了分页、排序、筛选功能,getRowIndex 返回的是当前可见页的行索引,如果你需要拿到原始数据源的索引,建议在原始数据的每一行增加唯一标识字段,通过唯一标识去匹配原始数组中的位置修改数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:45:03