我有2组独特的复选框,每个复选框都有自己的字段,其中一些被选中,所以我想在页面加载时默认选中这些复选框,但由于某种原因,它只选中了最后一个复选框,忽略了第一个列表
您可以在codesandbox上查看
import React, { Component, useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import { Checkbox, Pane, Label } from "evergreen-ui";
function ControlledCheckboxExample() {
const [checked, setChecked] = React.useState(true);
const [fieldchecked, setIsFieldChecked] = React.useState(false);
const [editContactFields, setContactFields] = React.useState([]);
useEffect(() => {
loaddata();
}, []);
const loaddata = () => {
let data = [
{
id: 1,
label: "First Checkbox",
type: "checkbox",
selectedvalue: [
{
value: "one"
},
{
value: "two"
}
],
hasvalue: true,
tag: "UNIQUEONE",
options: [
{
value: "one",
text: "one"
},
{
value: "two",
text: "two"
},
{
value: "three",
text: "three"
},
{
value: "four",
text: "four"
}
],
visible: true
},
{
id: 2,
label: "Second Checkbox",
type: "checkbox",
selectedvalue: [
{
value: "five"
}
],
hasvalue: true,
tag: "UNIQUETWO",
options: [
{
value: "five",
text: "five"
}
],
visible: true
}
];
setContactFields(data);
data.map((field, index) => {
if (field.type === "checkbox" && field.hasvalue == true) {
setIsFieldChecked(false);
let value = field.selectedvalue;
let tag = field.tag;
value.map((realvalue) => {
let fieldvalud = realvalue.value;
setIsFieldChecked((fieldchecked) => ({
...fieldchecked,
[fieldvalud + tag]: !fieldchecked[fieldvalud + tag]
}));
});
}
});
};
const handlefieldchecked = (a, f) => {
const fieldvalud = a;
const tag = f;
setIsFieldChecked((fieldchecked) => ({
...fieldchecked,
[fieldvalud + tag]: !fieldchecked[fieldvalud + tag]
}));
};
return (
<Pane>
{editContactFields.map((field) => (
<Pane>
<Label>
{field.label} {field.required == true && "*"}
</Label>
{field.options.map((checkboxfield) => (
<Checkbox
name={field.tag + "[]"}
id={field.tag}
type={field.type}
value={checkboxfield.value}
label={checkboxfield.text}
checked={fieldchecked[checkboxfield.value + field.tag]}
required={field.required}
onChange={(e) =>
handlefieldchecked(checkboxfield.value, field.tag)
}
/>
))}
</Pane>
))}
</Pane>
);
}
ReactDOM.render(<ControlledCheckboxExample />, document.getElementById("root"));
当我删除第二组复选框时,它就像它应该的那样工作,但一旦我添加它,它就会忽略第一组。
有没有办法让它正常工作?
1条答案
按热度按时间luaexgnf1#
当你在
data
上Map时,你用setIsFieldChecked(false);
重置fieldchecked
,这将导致只有最后一次迭代的值。