【发布时间】:2020-07-06 04:03:36
【问题描述】:
我正在尝试实现 Material UI IconButton 的 onClick(),它将 减少 或 增加 卡路里 表中每个元素的值,像这样。我的代码基于Table React component page code.
在这种情况下,如果我点击 [ - ] 按钮,它会将值递减为 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 (g)</TableCell>
<TableCell align="right">Carbs (g)</TableCell>
<TableCell align="right">Protein (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>
);
}
在 2 IconButtons 中,我尝试使用 onClick() 减少或增加 Calories 的值,但我这样做的方式不起作用。我该怎么办?我想我需要使用组件state,因此需要使用setState()函数,但我不知道如何分配它并获得该值。
【问题讨论】:
标签: javascript arrays reactjs button material-ui