React MUI-Datatables 获取行 ID

React MUI-Datatables get row id

我有一个 table 呈现两个按钮,删除和编辑行。

我需要在两者上访问行 ID。

我尝试使用 customBodyRender 但它没有用,我只有 dataIndex 和 rowIndex,但我需要的是实际的行对象值。

用代码更新了问题

const columns = [
{
  name: "id",
  label: "Id",
  options: {
    display: false
  }
},
{
  name: "name",
  label: "Name",
},
{
  name: "Actions",
  options: {
    filter: false,
    sort: false,
    empty: true,
    customBodyRender: (dataIndex, rowIndex) => {
      return (
        <>
          <IconButton aria-label="edit" onClick={() => {
            alert(dataIndex + " - " + rowIndex)
          }}>
            <EditIcon />
          </IconButton>
          <IconButton color="primary" aria-label="delete" style={{ marginLeft: "10px" }} onClick={() => {
            alert(dataIndex)
          }}>
            <DeleteIcon />
          </IconButton>
        </>
      );
    }
  }
}];

这就是 MUIDataTable 的使用方式

<MUIDataTable
      title={"Lista de Turnos"}
      data={shifts}
      columns={columns}
      options={{
        selectableRowsHideCheckboxes: true,
        textLabels: {
          body: {
            noMatch: 'Não foram encontrados registros para serem mostrados',
          },
        },
      }}
    />

您可以使用 customBodyRenderLite 而不是 customBodyRender

如果你想访问实际的数据对象,实际的代码应该是这样的。

import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import Button from '@material-ui/core/Button'

function App() {

  const data = [
    {id:1,name:'wahid'},
    {id:2,name:'jamil'},
    {id:3,name:'marin'},
  ];

  const columns = [
    {
      name: "id",
      label: "Id",
      options: {
        display: false
      }
    },
    {
      name: "name",
      label: "Name",
    },
    {
      name: "Actions",
      options: {
        filter: false,
        sort: false,
        customBodyRenderLite: (dataIndex, rowIndex) => {
          return (
              <Button aria-label="edit" onClick={() => {
                alert(data[dataIndex].name)
              }}>
                Button
              </Button>
              
          );
       }
    },
    
  }
  ];


  return (
    <React.Fragment>
      <MUIDataTable
        title={"ACME Employee list"}
        data={data}
        columns={columns}
          options={{
            selectableRowsHideCheckboxes: true,
            textLabels: {
              body: {
                noMatch: 'Não foram encontrados registros para serem mostrados',
              },
            },
          }}
      />
    </React.Fragment>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));