复选框要添加到数组上的功能组件,在窗体上 [英] Checkbox items to be added on Array with functional components on form
问题描述
我需要将复选框选中的项目添加到相应的数组中,因为我是React的新手,所以只需要有关它的指导即可.
I need to add checkbox checked items to respective array, as I am new into React so just need guidance about it.
这是我的数组
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
推荐答案
这将使您获得 checkboxItems
;当用户点击提交或执行其他任何操作时,您会在 checkboxItems
中有一个复选框列表,其中包含有关选中哪些项目和不选中哪些项目的信息.
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);
这篇关于复选框要添加到数组上的功能组件,在窗体上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!