Создать динамический столбец действий c в таблице пользовательского интерфейса React Material - PullRequest
1 голос
/ 17 февраля 2020

У меня есть компонент DataTable, содержащий таблицу React материала. Я передаю данные столбца и строки в качестве реквизита компоненту DataTable. Теперь я хотел добавить столбец действий с такими опциями, как редактировать и удалять. Я застрял здесь. Я предоставляю свой код ниже, пожалуйста, предоставьте решение

<DataTable
                    columns={COLUMN_DATA}
                    columnsUniqueKey='colId'
                    rowsUniqueKey='rowId'
                    rows={ROW_DATA}
                    pagination={false}
 /> 

import React from 'react';
import moment from "moment";
import StatusLabel from "../../../../components/StatusLabel/StatusLabel";
import { Button } from '@material-ui/core';


export const COLUMN_DATA = [
    {
        id: "key",
        label: "Key",
    },
    {
        id: "value",
        label: "Value",
    },
    {
        id: "createdAt",
        label: "Create At",
    },
    {
        id: "updatedAt",
        label: "Updated At",
    },
    {
        id: "actions",
        label: "Actions",
    }
]


const createData = (key, value, createdAt, updatedAt, actions) => {
    return {
        key,
        value,
        createdAt,
        updatedAt,
        actions
    };
}


export const ROW_DATA = [
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(1, 'day').format('LLL'),
        moment().subtract(1, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(2, 'day').format('LLL'),
        moment().subtract(2, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(3, 'day').format('LLL'),
        moment().subtract(3, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(4, 'day').format('LLL'),
        moment().subtract(4, 'day').format('LLL'),
        <>
            <Button  variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
    createData(
        'IP',
        '12.22.12.10',
        moment().subtract(5, 'day').format('LLL'),
        moment().subtract(5, 'day').format('LLL'),
        <>
            <Button variant="outlined" size="small" color="primary">
                Edit
            </Button>
        </>
    ),
];

И мой файл компонента DataTable

import React from 'react';
// styles
import useStyles from "./styles";
import {
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow,
    TableSortLabel
} from '@material-ui/core';
import { DATA_TABLE_ROWS_PER_PAGE_OPTIONS } from './constants';



const DataTable = ({ columns, rows, enableActions, pagination, ...props }) => {


  const classes = useStyles();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = event => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };


  //Row Click Event
  const onRowClicked = row => (event) => {
    // props.rowClicked(row)
  }



  return (
      <>
        <TableContainer className={classes.container}>
            <Table stickyHeader>
            <TableHead>
                <TableRow>
                {columns.map(({sortable, ...column}) => (
                    <TableCell
                    key={column[props.columnsUniqueKey]}
                    align={column.align}>
                        { sortable ? <TableSortLabel>
                                        {column.label}
                                     </TableSortLabel> : column.label }
                    </TableCell>
                ))}

                {/* { enableActions && <TableCell>
                    Actions
                </TableCell> } */}


                </TableRow>
            </TableHead>
            <TableBody>
                { ( pagination ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows).map(row => {
                return (
                    <TableRow onClick={onRowClicked(row)} hover role="checkbox" tabIndex={-1} key={row[props.rowsUniqueKey]}>
                        { columns.map( column => {
                            const value = row[column.id];
                            return (
                                <>
                                    <TableCell key={column[props.columnsUniqueKey]} align={column.align}>
                                        { column.format && typeof value === 'number' ? column.format(value) : value }
                                    </TableCell>
                                </>
                            );
                        }) }
                        {/* { enableActions && <TableCell> Actions </TableCell> } */}
                    </TableRow>
                );
                })}
            </TableBody>
            </Table>
        </TableContainer>
        {pagination && <TablePagination
            rowsPerPageOptions={DATA_TABLE_ROWS_PER_PAGE_OPTIONS}
            component="div"
            count={rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onChangePage={handleChangePage}
            onChangeRowsPerPage={handleChangeRowsPerPage}
        />}
      </>
  );
}

export default DataTable;

Как добавить обработчики для кнопки редактирования и передать данные столбца, чтобы я мог обрабатывать событие родительский компонент

...