Как я могу добавить новую редактируемую строку текстового поля в таблицу в реакции? - PullRequest
0 голосов
/ 07 ноября 2019

Как я могу добавить новую редактируемую строку текстового поля в таблицу в реаги? Всякий раз, когда я добавляю кнопку «Добавить», она просто добавляет новую строку таблицы, которая по умолчанию недоступна для редактирования. Логика определяется внутри add 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;

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 07 ноября 2019

Не уверен, что я правильно понимаю вашу точку зрения, но если вам нужно, чтобы строка была редактируемой при добавлении новых данных, то вот что вы должны делать:

Прежде всего, для вашего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]);
  };
0 голосов
/ 07 ноября 2019

Попробуйте использовать новые данные в addNewUserHandler, как показано ниже:

let newData = {
      id: "",
      name: "",
      calories: "",
      fat: "",
      carbs: "",
      protein: ""
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...