问题
I need to add checkbox checked items to respective array, as I am new into React so just need guidance about it.
This is my Array
items:[
{
id: 3,
name: "Leanne Graham",
email: "Sincere@april.biz",
link: "www.abc.com",
gender:"Female",
hobbies:"playing_games",
},
.
.
]
This is my Checkbox on form.
Suppose If I check playing games it should add to that respective array. So how can I do it with hooks, Do I need to pass object initially on items like this or something else.
items:[
{
id: 3,
name: "Leanne Graham",
email: "Sincere@april.biz",
link: "www.abc.com",
gender:"Female",
hobbies:"playing_games:true",
},
.
.
]
I tried to follow this, but if you can please let me know how can I do it then I will appreciate. Thanks
回答1:
This will allow you to get the checkboxItems
; When a use clicks submit or whatever other action then you have a list of checkboxes in checkboxItems
and which contains info about which items are checked and which aren't.
const CheckboxForm = () => {
// Put whatever checkboxes you want in here or pass in as props if that's better
const initialCheckboxes = [{ name: "test", checked: false}];
const [checkboxItems, setCheckboxItems] = useState(initialCheckboxes);
return (
<div>
{
checkboxItems.map((checkbox, index) =>
<div>
<p>{checkbox.name}</p>
<input
type={"checkbox"}
onChange={e => {
const newCheckboxes = [...checkboxItems];
newCheckboxes[index].checked = e.target.checked;
setCheckboxItems(newCheckboxes);
}}
checked={checkbox.checked}
/>
</div>
)
}
</div>
);
};
If you only want checked items then you can filter them out like this:
const checkedItems = checkboxItems.filter(({ checked }) => checked);
回答2:
I think what you're asking is advice on how to maintain the hobbies within a user profile? This is completely subjective to how you are or want to store your information in your database. It falls in to the category of "there's more than one way to skin a cat".
Given the object you presented, I would probably do it like this:
items:[
{
id: 3,
name: "Leanne Graham",
email: "Sincere@april.biz",
link: "www.abc.com",
gender:"Female",
hobbies: [
{playing_games: true},
{watching_tv: false},
],
},
]
This way, you could iterate over the hobbies and populate the checkboxes very easily.
来源:https://stackoverflow.com/questions/62388234/checkbox-items-to-be-added-on-array-with-functional-components-on-form