我是网络开发新手,我不知道如何完成这项任务。这是问题陈述。
给定三个复选框 如果选择 box1 然后选择 box2 它应该显示标记。现在,如果我选择 box3,那么 box1 应该自动取消选中并且必须反映在 UI 中。
这是我正在尝试的代码示例。
export default function CheckboxesGroup() {
const classes = useStyles();
const [state, setState] = React.useState({
gilad: true,
jason: false,
antoine: false,
});
const handleChange = (event) => {
setState({ ...state, [event.target.name]: event.target.checked });
};
const { gilad, jason, antoine } = state;
const error = [gilad, jason, antoine].filter((v) => v).length !== 2;
return (
<div className={classes.root}>
<FormControl required error={error} component="fieldset" className={classes.formControl}>
<FormLabel component="legend">Pick two</FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox checked={gilad} onChange={handleChange} name="gilad" />}
label="Gilad Gray"
/>
<FormControlLabel
control={<Checkbox checked={jason} onChange={handleChange} name="jason" />}
label="Jason Killian"
/>
<FormControlLabel
control={<Checkbox checked={antoine} onChange={handleChange} name="antoine" />}
label="Antoine Llorca"
/>
</FormGroup>
<FormHelperText>You can display an error</FormHelperText>
</FormControl>
</div>
);
}
答案 0 :(得分:0)
如果您只有 3 个选项,那么您可以为选中的项目设置特定条件 通过像这样改变handleChange函数
const handleChange = (event) => {
const {name, checked} = event.target;
let newState = {};
if([gilad, jason, antoine].filter((v) => v).length === 2 && checked === true){
if(name === 'gilad'){
newState = {jason: false};
} else if(name === 'jason'){
newState = {gilad: false};
} else if(name === 'antoine'){
newState = {gilad: false};
}
}
setState({ ...state,...newState, [name]: checked });
};
答案 1 :(得分:0)
不确定我是否正确理解您的问题,如果我误解了问题,请告诉我。据我了解,您试图强制用户最多选择 2 个框,进一步选择将取消最早的选择。
对于这个问题,我们可以了解到选择的顺序很重要,但是您使用的数据结构并没有反映这一点。您现在正在使用
$ kubectl apply -f cluster-scope-permissions.yml
clusterrole.rbac.authorization.k8s.io/cluster-scope-role created
clusterrolebinding.rbac.authorization.k8s.io/cluster-scope-rolebinding created
$ kubectl get nodes --as=system:serviceaccount:dxf-uat:dxf-deployer
NAME STATUS ROLES AGE VERSION
node1 Ready <none> 5h11m v1.18.12-gke.1210
node2 Ready <none> 5h11m v1.18.12-gke.1210
$ kubectl get persistentvolumes -n dxf-uat --as=system:serviceaccount:dxf-uat:dxf-deployer
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
pvc-0ba2fd12-c883-45b8-b52d-a6c826a2775a 8Gi RWO Delete Bound default/my-jenkins standard 131m
pvc-b4b7a4c8-c9ad-4e83-b1ee-663b3e4d938b 10Gi RWO Delete Bound default/debug-pvc standard 5h12m
作为状态,不包含检查顺序的信息。在这种情况下,我建议改用数组,这样可以更轻松地跟踪订购信息。
{
gilad: true,
jason: false,
antoine: false,
}
对于 const [state, setState] = React.useState(['gilad']);
const handleChange = (event) => {
const { name, checked } = event.target;
// handles unchecking the checked box
if (!checked) {
setState(prev => prev.filter(n => n !== name));
} else {
const stateWithNewName = [...state, name];
// only take the latest two names
setState(stateWithNewName.slice(-2));
}
};
const error = state.length !== 2;
组件,
Checkbox