Material UI IconButton onClick 增加或减少值

Gra*_*our 6 javascript arrays button reactjs material-ui

我试图执行onClick()一个的材料UI IconButton,这将减小增加卡路里每个元素的值在表中,像这样的。我的代码基于Table React 组件页面代码。

在此处输入图片说明

在这种情况下,如果我单击[ - ]按钮,就会递减的值设置为2,并且如果我在[+]按钮点击,将递增的值至4。

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import IconButton from '@material-ui/core/IconButton';

//Icons
import AddCircleOutlineRoundedIcon from '@material-ui/icons/AddCircleOutlineRounded';
import RemoveCircleOutlineRoundedIcon from '@material-ui/icons/RemoveCircleOutlineRounded';

/*------------------------- IMPORTS ---------------------------*/

const useStyles = makeStyles({
  table: {
    minWidth: 650,
  },
});

function createData(name, calories, fat, carbs, protein) {
  return { name, calories, fat, carbs, protein };
}

const rows = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

export default function DenseTable() {
  const classes = useStyles();

  return (
    <TableContainer component={Paper}>
      <Table className={classes.table} size="small" aria-label="a dense table">
        <TableHead>
          <TableRow>
            <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>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map(row => (
            <TableRow key={row.name}>
              <TableCell component="th" scope="row">
                {row.name}
              </TableCell>

/* ----------------- IconButton HERE ---------------- */

              <TableCell align="right">
              <IconButton onClick={ --row.calories }>
              <RemoveCircleOutlineRoundedIcon />
              </IconButton> 
              {row.calories} 
              <IconButton onClick={ ++row.calories }>
              <AddCircleOutlineRoundedIcon />
              </IconButton>
              </TableCell>

/* ----------------- IconButton END ---------------- */

              <TableCell align="right">{row.fat}</TableCell>

              <TableCell align="right">{row.carbs}</TableCell>

              <TableCell align="right">{row.protein}</TableCell>

            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
Run Code Online (Sandbox Code Playgroud)

在 2 中IconButtons,我试图使用 减少或增加CaloriesonClick(),但我这样做的方式不起作用。我该怎么办?我想我需要使用组件state,因此需要使用setState()函数,但我不知道如何分配它并获得该值。

Pus*_*kin 4

是的,您必须setStateonClick. 我指出你所犯的错误后,我会告诉你如何做。

你在这里犯的错误很少,

错误1:没有保持rowReact状态。所有动态数据必须存储为 React State。

错误2: onClick不是函数而是数字。--row.Calorie不是一个函数,它是一个输出数字的表达式。

错误3:直接改变数据。这在 React 和函数式编程中是严格禁止的。您不应该键入诸如 之类的表达式--row.Calorie。它们直接改变数据,而 React 无法跟踪这些变化。

进行这些调整后就可以开始了。


// Straight away create a row state like this.
const [rows, setRows] = useState([
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
])

// inside map function
rows.map((row, index) => (
  // ...
  <IconButton
    // pass a function instead of expression
    onClick={() => {
      // NOTE: I'm using only index and prev in this block
      // and not using row, or directly mutating them
      setRows(prev => [
        ...prev.slice(0, index),
        { ...prev[index], calories: prev[index].calories - 1 }, 
        ...prev.slice(index + 1)
      ])
      // Also NOTE: I'm creating a new state
      // from the previous state - `prev` without
      // mutating the `prev`
    }}
  >
    <RemoveCircleOutlineRoundedIcon />
  </IconButton>
  // ...

))

Run Code Online (Sandbox Code Playgroud)