我是 React 新手,我正在尝试编写一个包含不同组的组件,每个组都累积了一定数量的点,每个组包含不同的复选框,我希望当单击复选框时,数量会以正确的方式更新(添加/减去取决于复选框状态)
这是我尝试检查其是否正常工作的代码(我省略了不相关的代码并包含):
export default function Tracker() {
const [amountMust, setAmountMust] = React.useState(0); // 84
const [amountListA, setAmountListA] = React.useState(0); // 24.5
const [amountMalag, setAmountMalag] = React.useState(0); //6
const [amountSport, setAmountSport] = React.useState(0); //2
const [amountScience, setAmountScience] = React.useState(0); // 8
const [amountGeneral, setAmountGeneral] = React.useState(0); // 2
const [amountProject, setAmountProject] = React.useState(0); // 2
const [amountEnglish, setAmountEnglish] = React.useState(0); // 2
const courses = [
{ number: "101", name: "Mathematics", points: 3 },
{ number: "102", name: "Physics", points: 4 },
{ number: "103", name: "Chemistry", points: 2 },
];
const CheckBoxState = ({ points, groupSetter }) => {
const [isChecked, setIsChecked] = React.useState(false);
const handleCheckboxChange = (e) => {
const newChecked = e.target.checked;
setIsChecked(newChecked);
groupSetter ((prevGroupPoints) =>
newChecked ? prevGroupPoints + points : prevGroupPoints - points);
};
return (
<Checkbox
variant="soft"
size="md"
color="success"
checked={isChecked}
onChange={handleCheckboxChange}
/>
);
};
const CourseList = ({ courses }) => {
return (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
{courses.map((course) => (
<FormControl
sx={{
display: "flex",
flexDirection: "row",
gap: 1,
border: "1px solid #ccc",
borderRadius: 2,
padding: 2,
}}
>
<Box sx={{ display: "fixed", alignItems: "center", gap: 2 }}>
<CheckBoxState points={course.points} groupSetter={setAmountMust}/>
<Typography variant="body2">{course.number}</Typography>
<Typography variant="body2">{course.name}</Typography>
<Typography variant="body2">נק"ז: {course.points}</Typography>
</Box>
<Box sx={{ display: "flex", gap: 2, mt: 2, marginLeft: 1 }}>
<FormControl>
<FormLabel>Option 1</FormLabel>
<Switch size="sm" />
</FormControl>
<FormControl>
<FormLabel>Option 2</FormLabel>
<Switch size="sm" />
</FormControl>
</Box>
</FormControl>
))}
</Box>
);
};
return (
<div className='box'>
<CourseList />
</div>
);
}
问题是当调用时,groupSetter
复选框状态不会改变且保持未选中状态,并且每次单击时都会一遍又一遍地handleCheckboxChange
添加该值,但是当删除或传递不依赖于先前状态的常规值时,它就会起作用。amountMust
groupSetter
将状态设置器和值传递给复选框组件的目的是因为我想在代码中将此组件用于不同的组。