我在表中有一个图标列表,单击该图标时,整个图标列表更改为另一个图标。我应该如何阻止它们同时更改?
代码:
import React from 'react';
import {makeStyles, Theme} 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 TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import FilterListIcon from '@material-ui/icons/FilterList';
import FavoriteBorderOutlinedIcon from '@material-ui/icons/FavoriteBorderOutlined';
import FavoriteOutlinedIcon from '@material-ui/icons/FavoriteOutlined';
...
export default function Table() {
...
const [isFavorite, setIsFavorite] = React.useState(false);
...
return (
...
return (
<TableRow
hover
tabIndex={-1}
key={row.name}>
<TableCell>{row.name}</TableCell>
...
<TableCell>
<IconButton onClick={() => setIsFavorite(!isFavorite)}>
{isFavorite ? <FavoriteOutlinedIcon color="secondary"/> : <FavoriteBorderOutlinedIcon color="action"/> }
</IconButton>
</TableCell>
...
);
}
答案 0 :(得分:1)
您的状态isFavorite每次单击都会被切换。要获得所需的功能,您需要在图标对象上具有一个收藏夹属性。这是一个示例:
const [iconData, setIconData] = useState([
{icon: someIcon, id: 1, isFavorite: false},
{icon: diffIcon, id: 2, isFavorite: false},
{icon: thirdIcon, id: 3, isFavorite: false}
])
在return语句中,您将希望映射到iconData
iconData.map(icon => (
<TableCell key={icon.id}>
<IconButton onClick={() => iconFavChange(icon.id)}>
{icon.isFavorite ? <FavoriteOutlinedIcon color="secondary"/> :
<FavoriteBorderOutlinedIcon color="action"/> }
</IconButton>
</TableCell>
))
更改手柄图标
const iconFavChange =(id)=> {
let updatedIconData = iconData.map(icon => icon.id === id ? icon.isFavorite = !icon.isFavorite : icon)
// map over existing state data and if the id in args matches id of icon,
//then toggle the isFavorite property
setIconData(updatedIconData)
}
编辑:
const [data, setData] = React.useState(rows);
isFavorite: boolean;
const handleFavoriteToggle = name => {
console.log(name);
let updatedData = data.map(row => {
if (row.name === name) {
row.isFavorite = !row.isFavorite;
}
return row;
});
setData(updatedData);
};
<IconButton onClick={() => handleFavoriteToggle(row.name)}>
{row.isFavorite ? (<FavoriteOutlinedIcon color="secondary" />)
: (<FavoriteBorderOutlinedIcon color="action" />)}
</IconButton>
<TableBody>
{stableSort(data, getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => {