React:点击按钮时创建全选/取消全选复选框



我正在复选框列表中显示数据。如何实现全选和取消全选按钮,用于选择所有复选框或取消选中所有复选框。

请在下面的沙箱中找到我的react代码和来自api的数据:https://codesandbox.io/s/immutable-pond-07qnue

[ {"templateID":"11","templateName":"All” }, {"templateID":"21","templateName":"SC" }]

感谢

首先,获取数据,然后创建一个数组:-

const getData = () => {
let LIBID = JSON.parse(localStorage.getItem("user")).libid;
let url = `${checkWindowName}/getmanualout?LibraryId=${LIBID}`;
fetch(url, {
method: "GET",
headers: {
Accepts: "application/json",
"content-type": "application/json",
},
})
.then((result) => {
result.json().then((resp) => {
console.log("result 1:- ", resp.data);
if (resp.response === "Success") {
let dt = [];
for (let i = 0; i < resp.data.length; i++) {
dt.push({
type: resp.data[i].type,
uniqueid: resp.data[i].uniqueid,
checkbox: false, // -------create here-------
id: i,
});
}
setPosts(dt);
setloader(false);
setexcelbutton(false);
console.log("data :- ", dt);

}
});
})
.catch(() => {

});
};

第二,我打印数据:-

<table className="table table-hover" id="table-to-xls">
<thead>
<tr>
<th >
<input type="checkbox" onClick={() => allCheckTrue(allTrue)}/>
</th>
<th>Unique ID</th>
<th>Type</th>
</tr>
</thead>
{posts.map((item, i) => {
return (
<React.Fragment key={i}>
<tbody>
<tr>
<th onClick={() => checkBoxTrueSinghle(item)}>
<input type="checkbox"  checked={item.checkBox}></input>
</th>
<td className="sz-arg-tb wd-11 pr-2">
<p>{item.uniqueid}</p>
</td>

<td className="sz-arg-tb wd-11 ">
<p>{item.type}</p>
</td>
</tr>
</tbody>
</React.Fragment>
);
})}
</table>

第三,创建函数:-

//All checkbox true
const allCheckTrue = (allTrue) => {
console.log("all true :- ", allTrue);
let data = posts;
let dt = [];
for (let i = 0; i < data.length; i++) {
if (allTrue === true) {
dt.push({
type: data[i].type,
uniqueid: data[i].uniqueid,
checkBox: false,
id: i,
});
setAllTrue(false);
} else {
dt.push({
type: data[i].type,
uniqueid: data[i].uniqueid,
checkBox: true,
id: i,
});
setAllTrue(true);
}
setPosts(dt);
console.log("check :- ", dt);
}
};

对于单次结账真:-

const singleCheckBox = (item) => {
console.log("item true :- ", item);
var check = posts.findIndex((el) => el.id === item.id);
const checkbox_true = [...posts];
console.log(checkbox_true[check].checkBox);
if (checkbox_true[check].checkBox === true) {
checkbox_true[check].checkBox = false;
setPosts(checkbox_true);
} else {
checkbox_true[check].checkBox = true;
setPosts(checkbox_true);
}
console.log("check :- ", checkbox_true);
};

最新更新