我如何在表中添加新的可编辑文本字段行?

时间:2019-11-07 08:16:25

标签: javascript reactjs material-ui

如何在表中添加新的可编辑文本字段行? 每当我添加单击添加按钮时,它只会添加一个默认情况下不可编辑的新表行。逻辑是在add addNewUserHandler内部定义的,该addNewUserHandler应该添加新的文本字段行,而只是添加不可编辑的表行。

import React, { useState } from "react";
import { Table } from "@material-ui/core";
import { Paper } from "@material-ui/core";
import {
  TableHead,
  TableBody,
  TableCell,
  TableRow,
  Button,
  makeStyles,
  Icon,
  Tooltip,
  TextField
} from "@material-ui/core";
import InputBase from "@material-ui/core/InputBase";
import DeleteIcon from "@material-ui/icons/Delete";
import AddIcon from "@material-ui/icons/Add";
import CheckIcon from "@material-ui/icons/Check";
import Fab from "@material-ui/core/Fab";
import SearchIcon from "@material-ui/icons/Search";
import CloseIcon from "@material-ui/icons/Close";
import EditIcon from "@material-ui/icons/Edit";


const useStyles = makeStyles(theme => ({
  root: {
    width: "100%"
  },
  paper: {
    marginTop: theme.spacing(3),
    width: "100%",
    overflowX: "auto",
    marginBottom: theme.spacing(2)
  },
  table: {
    minWidth: 650
  }
}));

const Userdata = () => {
  const [data, setdata] = useState([
    {
      id: 1,
      name: "Frozen yoghurt",
      calories: 159,
      fat: 6.0,
      carbs: 24,
      protein: 4.0,
    },
    {
      id: 2,
      name: "Ice cream sandwich",
      calories: 237,
      fat: 9.0,
      carbs: 37,
      protein: 4.3,
      
    },
    { id: 3, name: "Eclair", calories: 300, fat: 7.0, carbs: 67, protein: 4 },
    {
      id: 4,
      name: "Velvet cake",
      calories: 237,
      fat: 2.5,
      carbs: 17,
      protein: 3,
    }
  ]);

 
  const [editingIndex, setEditingIndex] = useState(-1);



  const addNewUserHandler = () => {
    let newData = [{
      id: "",
      name: "",
      calories: "",
      fat: "",
      carbs: "",
      protein: ""
    }];
    const Data = data;
    console.log(newData)
    setdata([...Data, newData])
 
  };

  const addNewData = e => {
    console.log(e);
  };

  const startEditing = i => {
    setEditingIndex(i);
  };

  const stopEditing = () => {
    setEditingIndex(-1);
  };

  const inputChangeHandler = (e, i) => {
    let result = data.map((data) =>{
     return data.id === i ? {...data, [e.target.name]:e.target.value} : {...data}
    })
     setdata(result)
  
  }

  const submitInputHandler = () => {
    setEditingIndex(-1);
  };

  const deleteRowHandler = id => {
    const temp = [...data];
    const filteredData = temp.filter(data => data.id !== id);
    setdata([...filteredData,]);
  };

  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Table className={classes.table} size="small">
          <TableHead>
            <TableRow>
              <TableCell>Id.</TableCell>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell align="right">Calories</TableCell>
              <TableCell align="right">Fat&nbsp;(g)</TableCell>
              <TableCell align="right">Carbs&nbsp;(g)</TableCell>
              <TableCell align="right">Protein&nbsp;(g)</TableCell>
              <TableCell align="right">
                <InputBase
                  placeholder="search"
                  inputProps={{ "aria-label": "search" }}
                  style={{ verticalAlign: "middle" }}
                />
                <SearchIcon style={{ verticalAlign: "middle" }} />
              </TableCell>
              <TableCell align="right">
                <Tooltip title="Add data" aria-label="add">
                  <Fab
                    color="primary"
                    className={classes.fab}
                    onClick={addNewUserHandler}
                  >
                    <AddIcon />
                  </Fab>
                </Tooltip>
              </TableCell>
            </TableRow>
          </TableHead>

          <TableBody>
            {data.map((data, id) => (
              <TableRow key={id}>
                  {editingIndex === data.id ? (
                <TableCell component="th" scope="row">
                    <TextField
                      style={{ width: "3rem" }}
                      name="id"
                      onChange={(e) =>inputChangeHandler(e, data.id)}
                      value={id+1}
                    />
                    </TableCell>
                  ) : 
                  (
                  <TableCell component="th" scope="row">
                   {id+1}
                </TableCell>
                
                  )}
                  {editingIndex === data.id ? (
                    <TableCell>
                      <TextField
                    style={{ width: "8rem" }}
                    onChange={(e) =>inputChangeHandler(e, data.id)}
                    name="name"
                    value={data.name}
                    />
                    </TableCell>
                    
                  ) : (
                  <TableCell style={{ textAlign: "center" }}>
                    {data.name}
                </TableCell>
                  )}
                  {editingIndex === data.id ? (
                <TableCell align="center">
                    <TextField
                      style={{ width: "8rem" }}
                      onChange={(e) =>inputChangeHandler(e, data.id)}
                      name="calories"
                      value={data.calories}
                      />
                      </TableCell>
                  ) : (
                    <TableCell style={{ textAlign: "center" }}>
                      {data.calories}
                    </TableCell>
                  )}
                {editingIndex === data.id ? (
                <TableCell>
                  <TextField
                    style={{ width: "8rem" }}
                    onChange={(e) =>inputChangeHandler(e, data.id)}
                    name="fat"
                    value={data.fat}
                  />
              </TableCell>
                ) : (
                  <TableCell style={{ textAlign: "center" }}>
                    {data.fat}
                  </TableCell>
                )}
                  {editingIndex === data.id ? (
                <TableCell align="center">
                    <TextField
                      style={{ width: "8rem" }}
                      onChange={(e) =>inputChangeHandler(e, data.id)}
                      name="carbs"
                      value={data.carbs}
                    />
                </TableCell>
                  ) : (
                    <TableCell style={{ textAlign: "center" }}>
                      {data.carbs}
                    </TableCell>
                  )}
                  {editingIndex === data.id ? (
                <TableCell align="center">
                    <TextField
                    disabled={false}
                      style={{ width: "8rem" }}
                      onChange={(e) =>inputChangeHandler(e, data.id)}
                      name="protein"
                      value={data.protein}
                    />
                </TableCell>
                  ) : (
                    <TableCell style={{ textAlign: "center" }}>
                    {data.protein}
                    </TableCell>
                  )}
                <TableCell style={{ textAlign: "center" }}>
                  {editingIndex !== data.id ? (
                    <EditIcon onClick={() => startEditing(data.id)} style= {{cursor: "pointer"}}/>
                  ) : (
                    <CheckIcon onClick={submitInputHandler} style= {{cursor: "pointer"}} />
                  )}
                </TableCell>
                <TableCell>
                  {editingIndex !== data.id ? (
                    <DeleteIcon onClick={() => deleteRowHandler(data.id)} style= {{cursor: "pointer"}}/>
                  ) : (
                    <CloseIcon onClick={stopEditing} style= {{cursor: "pointer"}} />
                  )}
                </TableCell>
              </TableRow>
            ))}
            {/* <TableRow>
              <TablePagination
                count={rows.length}
                rowsPerPage={rowsPerPage}
                page={page}
                onChangePage={handleChangePage}
              />
            </TableRow> */}
          </TableBody>
        </Table>
      </Paper>
    </div>
  );
};

export default Userdata;

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试在addNewUserHandler中使用newData,如下所示:

let newData = {
      id: "",
      name: "",
      calories: "",
      fat: "",
      carbs: "",
      protein: ""
    };

答案 1 :(得分:0)

不确定我的意思是对的,但是如果您需要的是在添加新数据时使行可编辑,那么您应该这样做:

首先,为您的newData指定一个唯一的id,您可以为此使用uuid,如果您不构建实际的应用程序,则可以使用Math.random 。 然后在startEditing(newData.id)内部调用addNewUserHandler,如下所示:

const addNewUserHandler = () => {
    let newData = [
      {
        id: Math.ceil(Math.random() * 9999),
        name: "",
        calories: "",
        fat: "",
        carbs: "",
        protein: ""
      }
    ];
    const Data = data;
    startEditing(newData.id)
    setdata([...Data, newData]);
  };