如何使用嵌套对象数组呈现复选框
2022-04-21
4201
我有一个复选框组件,它可以呈现多个日期复选框。我需要打印所选复选框的值。下面给出的示例如下所示:
const [state, setState] = useState({
"firstName": "",
"lastName" : "",
"mobileNumber" : "",
"avalabilities": [{"availabilityId": "",
day: [
{
value: "sun",
name: "Sunday"
},
{
value: "mon",
name: "Monday"
},
{
value: "tue",
name: "Tuesday"
},
{
value: "wed",
name: "Wednesday"
},
{
value: "thur",
name: "Thursday"
},
{
value: "fri",
name: "Friday"
},
{
value: "sat",
name: "Saturday"
}
],
"isChecked": false,
"checked" : false,
"allChecked": false,
"error": null});
这是下面给出的控制台值
{firstName: '', lastName: '', mobileNumber: '', avalabilities: Array(1), …}
allChecked: false
avalabilities: Array(1)
0:
availabilityId: ""
day: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
close: false
disabled: false
error: null
firstName: ""
isChecked: false
isPending: false
lastName: ""
mobileNumber: ""
open: false
这是我尝试呈现数组的方式
{(avalabilities || [{}]).map((av, index) => {
return (
<div key={av.availabilityId}>
<>
{av.day.map((item) => {
return (
<div>
<input
checked={item.checked || false}
onChange={() => handleChange3(item.value)}
type="checkbox"
/>
</div>
);
})}
</>
但是使用日期数组进行映射时出现错误,如下所示
are not valid as a React child (found: object with keys {value, name}). If you meant to render a collection of children, use an array instead.
const checkedHandler = (event) => {
setState(...)
//Well, here I don't know how change the particular value of the
array...}
任何帮助都非常感谢。
1个回答
如果我没记错的话,您希望显示每个复选框的值,并在切换任何复选框时保存相应的复选框值。
您有
avalabilities
数组,并且在每个对象中我们都有另一个
day
数组。我渲染了所有的
avalabilities
。现在,当我切换任何复选框时,我会将三件事传递给 checkHandler:
-
e
,这是复选框的本机事件 -
avIndex
,这是avalabilities
数组中对象的索引 -
index
,这是 day 数组中对象的索引。
现在,每个 day 对象,我都设置一个键
checked
,并通过从
e.target.checked
获取值来存储该复选框的值。
希望这能解决您的问题
newState.avalabilities[avIndex].day[index].checked = e.target.checked;
import { useState } from 'react';
export default function App() {
const [state, setState] = useState({
firstName: '',
lastName: '',
mobileNumber: '',
avalabilities: [
{
availabilityId: '',
day: [
{ value: 'sun', name: 'Sunday' },
{ value: 'mon', name: 'Monday' },
{ value: 'tue', name: 'Tuesday' },
{ value: 'wed', name: 'Wednesday' },
{ value: 'thur', name: 'Thursday' },
{ value: 'fri', name: 'Friday' },
{ value: 'sat', name: 'Saturday' }
],
isChecked: false,
checked: false,
allChecked: false,
error: null
}
]
});
const checkedHandler = (e, avIndex, index) => {
console.log(e.target.checked, avIndex, index);
setState((prev) => {
let newState = { ...prev };
newState.avalabilities[avIndex].day[index].checked = e.target.checked;
return newState;
});
};
return (
<>
{state.avalabilities.map((av, avIndex) => (
<div key={av.availabilityId}>
{av.day.map((item, index) => (
<div key={index}>
<input
checked={item?.checked || false}
onChange={(e) => checkedHandler(e, avIndex, index)}
type='checkbox'
/>
<span>{item.name}</span>
</div>
))}
</div>
))}
</>
);
}
Nouman Rafique
2022-04-22