如何正确呈现数据网格列内的按钮或图标?

问题描述 投票:0回答:2

我有一个数据网格,其中有一列保存操作(编辑和删除)。

这是我的完整代码:

import React, { useEffect } from 'react'
import { DataGrid } from '@mui/x-data-grid'
import { useNavigate } from 'react-router-dom'
import EditIcon from '@mui/icons-material/Edit'
import DeleteForeverIcon from '@mui/icons-material/DeleteForever'
import { Button } from '@mui/material'

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    edit: EditIcon,
    delete: `${(<Button variant="text">Text</Button>)}`,
  },
]

const Colors = () => {

  const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'firstName', headerName: 'First name', width: 130 },
    { field: 'lastName', headerName: 'Last name', width: 130 },
    {
      field: 'age',
      headerName: 'Age',
      type: 'number',
      width: 90,
    },
    { field: 'edit', headerName: 'Edit', width: 150 },
    { field: 'delete', headerName: 'Delete', width: 150 },
  ]

  return (
    <div style={{ height: 560, width: '100%' }}>
      <DataGrid
        sx={{ backgroundColor: 'white' }}
        rows={rows}
        columns={columns}
        pageSize={8}
        rowsPerPageOptions={[8]}
        checkboxSelection
      />
    </div>
  )
}

export default Colors

现在我的问题是:我想在编辑栏中使用材质

icon

我尝试直接实现图标,如下所示:

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    edit: EditIcon, //<--
  },
]

或者通过这种方式调用

button

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    delete: `${(<Button variant="text">Text</Button>)}`,   //<--
  },
]

结果:我得到渲染

[object object]
而不是图标或按钮:

enter image description here

如何正确渲染数据网格列内的按钮或图标?

material-ui datagrid
2个回答
1
投票

我想你可以尝试这样做。 MUI 公开了一个操作列类型,您可以向其传递自定义图标和实现。如果您在此链接上向下滚动一点,您可以找到很多列选项。

行动栏

import { GridActionsCellItem, GridRowParams } from "@mui/x-data-grid-pro";
import EditIcon from "@mui/icons-material/Edit";

    {
      field: "actions",
      type: "actions",
      align: "left",
      headerName: t("actions"),
      getActions: (params: GridRowParams) => [
        <GridActionsCellItem
          key={0}
          icon={<EditIcon titleAccess={t("edit")} color="primary" />}
          label={t("edit")}
          onClick={() => handleEditPressed(params)}
        />,
      ],
    },

1
投票

我通过使用renderCell解决了我的问题,这样我就可以按照我想要的方式在网格数据内渲染html(例如我可以放置button):

{
   field: 'edit',
   headerName: 'Edit',
   width: 70,
   renderCell: (params) => {
     return <EditIcon />    //<-- Mui icons should be put this way here.
   },
},
© www.soinside.com 2019 - 2024. All rights reserved.