在react.js中编辑材料表单元格时,Onchange不起作用

时间:2019-10-01 07:04:20

标签: reactjs react-redux react-router

如何在带有Material-UI的React中创建可编辑单元格?我试图使单元格在材料UI表中可编辑,但是当我将inputChangeHandler传递给onChange方法时,它无法按预期工作,文本仅添加到新行中。

快照: the edited data shifted to the new table row

我正在使用react-hooks useState存储初始状态。

代码:

const MyForm = () => {
  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;
    // Data.push(newData)
    console.log(newData)
    setdata([...Data, newData])
 
  };

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

  // const editDataHandler = id => {
  //   // console.log(id);
  //   // setEditing(true)
  //     setEditingIndex(id)
  // };

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

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

  const inputChangeHandler = (e) => {
    // e.persist();
    // console.log(id, e.target.value, "e,target");
    setdata([{[e.target.name]: e.target.value}])

  };

  const submitInputHandler = (e) => {
    e.persist();
    console.log("this is the input change handler", e.target.value);
  };

  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)}
                      value={id+1}
                    />
                    </TableCell>
                  ) : 
                  (
                  <TableCell component="th" scope="row">
                   {id+1}
                </TableCell>
                
                  )}
                  {editingIndex === data.id ? (
                    <TableCell>
                      <TextField
                    style={{ width: "8rem" }}
                    onChange={(e) =>inputChangeHandler(e)}
                    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)}
                      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)}
                    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)}
                      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)}
                      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 MyForm;

1 个答案:

答案 0 :(得分:0)

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

}
//then 
onChange={(e) =>inputChangeHandler(e, data.id)}