如何解决如何在react中实现复选框选中和未选中的功能?
我试图在react中实现复选框,但是在选中和取消选中复选框时遇到问题。
我尝试实现onchange
处理程序。
onChange={() => {
// first approch
// i.checked = !i.checked;
// setObj({ ...i});
// second approach
setObj({ ...i,checked: !i.checked });
setTimeout(ab,2000);
}}
所以我使用了两种方法
在第一种方法中,我更改了toggle the checked
属性,然后创建了新的reference
效果很好
i.checked = !i.checked;
setObj({ ...i});
在第二种方法中,我使用toggle of checked property
创建了一个新对象或引用,但这为什么不起作用
{ ...i,checked: !i.checked }
为什么我的第一种和第二种方法不同?
这是我的代码
https://codesandbox.io/s/lucid-fire-cxp9c?file=/src/child.js:362-666
import React from "react";
export default function Child({ data,ab }) {
const [obj,setObj] = React.useState(null);
return (
<>
{data &&
data.map((i,idx) => {
return (
<ul key={idx}>
<li>
<input
type="checkbox"
checked={i.checked}
onChange={() => {
// first approch
// i.checked = !i.checked;
// setObj({ ...i});
// second approach
setObj({ ...i,2000);
}}
/>
{i.label}
</li>
{i.childrens && i.childrens.length > 0 ? (
<Child data={i.childrens} ab={ab} />
) : null}
</ul>
);
})}
</>
);
}
任何建议... !!?
解决方法
好吧,所以将状态和道具混合在一起会使它有些混乱。我做了一些重构,并为您使用的嵌套值树添加了一些递归。我在所做的更改上方添加了评论。
var data = [/* your array of data */]
// recursive function to find the value in the tree
const setChecked = (data,label) => {
if (!data || data.length === 0) return [];
// grab the first element
const [current,...rest] = data;
// if it's found,plop the element back into place with
// check changed and dump in the rest of the elements
if (current.label === label) {
return [
{
...current,checked: !current.checked,childrens: current.childrens.map((child) => ({
...child,checked: !current.checked
}))
},...rest
];
}
// re-slot the element and recursively move
// through the remaining siblings
return [
{
...current,childrens:
current.childrens.length > 0
? setChecked(current.childrens,label)
: current.childrens
},...setChecked(rest,label)
];
};
export default function App() {
const [state,setState] = React.useState(data1);
const handleChange = (data) => {
setState(setChecked(state,data.label));
};
const ab = () => {
console.log(JSON.stringify(state));
};
return (
<div className="App">
<Child data={state} ab={ab} handleChange={handleChange} />
</div>
);
}
// added the onChange handler to lift the state to the parent
export default function Child({ data,ab,onChange }) {
return (
<>
{data &&
data.map((i,idx) => {
return (
<ul key={idx}>
<li>
<input
type="checkbox"
checked={i.checked}
onChange={() => {
onChange(i);
setTimeout(ab,2000);
}}
/>
{i.label}
</li>
{i.childrens && i.childrens.length > 0 ? (
<Child data={i.childrens} ab={ab} onChange={onChange} />
) : null}
</ul>
);
})}
</>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。