首页 > 解决方案 > 如何在 data-grid 组件 column 组件中添加 Edit material-ui 图标

问题描述

我正在使用 material-ui data-grid,我想针对每一行显示 Edit material-ui 图标。但是在数据网格中,我们没有任何可以用于相同目的的道具。下面是源代码:

import React, {useState, useEffect} from "react";
import { DataGrid } from "@material-ui/data-grid";
import { Edit } from "@material-ui/icons";

    const MyComponent= () => {
          return (
             <DataGrid
              rows={[{name: "ABC", email: "xyz@gmail.com"}]}
              columns={[{ field: "name", headerName: "Name" }, { field: "email", headerName: "Email" }]}
            />
          )
};

export default MyComponent;

标签: javascripthtmlreactjsdatagridmaterial-ui

解决方案


import React, {useState, useEffect} from "react";
import { FormControlLabel, IconButton } from '@material-ui/core';
import { DataGrid } from "@material-ui/data-grid";
import EditIcon from '@material-ui/icons/Edit';
import { blue } from '@material-ui/core/colors';

    const MatEdit = ({ index }) => {

        const handleEditClick = () => {
            // some action
        }


        return <FormControlLabel
                   control={
                       <IconButton color="secondary" aria-label="add an alarm" onClick={handleEditClick} >
                           <EditIcon style={{ color: blue[500] }} />
                       </IconButton>
                   }
               />
    };

    const MyComponent= () => {
          const rows = [{ id: 1, name: "ABC", email: "xyz@gmail.com" }];
          const columns=[
                    { field: "name", headerName: "Name" }, 
                    { field: "email", headerName: "Email" },
                    {
                        field: "actions",
                        headerName: "Actions",
                        sortable: false,
                        width: 140,
                        disableClickEventBubbling: true,
                        renderCell: (params) => {
                            return (
                                <div className="d-flex justify-content-between align-items-center" style={{ cursor: "pointer" }}>
                                    <MatEdit index={params.row.id} />
                                 </div>
                            );
                         }
                      }
                  ];

          return (
             <div style={{ height: 500, width: 500 }}>
                 <DataGrid rows={rows} columns={columns} />
             </div>
          )
};

export default MyComponent;

单击此处查看演示。


推荐阅读