我创建一个表格来显示一些值
<TableContainer>
<Table sx={{ width: "100%" }}>
{listVersions
? listVersions.map((current_version, index) => {
const isItemSelected = isSelected(index+ 1);
const labelId = `enhanced-table-checkbox-${index}`;
return (
<TableRow
hover
onClick={() => handleClick(index + 1, current_version, isItemSelected)}
role="checkbox"
aria-checked={isItemSelected}
tabIndex={-1}
key={index + 1}
selected={isItemSelected}
sx={{ cursor: "pointer" }}
>
<TableCell padding="checkbox">
<Checkbox
color="primary"
checked={isItemSelected}
inputProps={{
"aria-labelledby": labelId,
}}
/>
</TableCell>
<TableCell>{current_version}</TableCell>
</TableRow>
我需要选择当前版本。 所以handleClick看起来像:
const handleClick = (id: number, version: string, isSelected: boolean) => {
console.log(version , isSelected);
......
}
正确的版本显示在控制台中,但其状态,无论是否选中,始终是相反的值。当我选择行时,值为 false,当我取消选择行时,值为 true。
选择行时预期值为 true。
我不明白哪里出了问题
handleClick
函数,isSelected
似乎是负责判断该行是否被选中的函数。您可以直接将选定的状态传递给 handleClick
函数,而不是依赖于 isSelected
函数。
<TableRow
hover
onClick={() => handleClick(index + 1, current_version, isItemSelected)}
role="checkbox"
aria-checked={isItemSelected}
tabIndex={-1}
key={index + 1}
selected={isItemSelected}
sx={{ cursor: "pointer" }}
>
修改您的
handleClick
函数以直接使用从 TableRow 组件传递的 isItemSelected
值
const handleClick = (id: number, version: string, isItemSelected: boolean) => {
console.log(version, isItemSelected);
// Other logic
};