我有一个React表渲染数据,我可以从mysql数据库中使用axios。每个表行都有复选框。我可以在<thead>
中使用该复选框选中/取消选中所有复选框。
我需要为函数deleteAll()
编写代码,并调用Delete按钮的onClick
事件(这将获取所有选中复选框的值,并将其传递给API,以删除将这些值作为ID的记录)
这是我的代码
import React from "react";
import axios from "axios";
import { useState, useEffect} from "react";
import { Link } from "react-router-dom";
import Table from 'react-bootstrap/Table'
import Dashboard from "../login/dashboard";
import { toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
const UserGroup = () => {
const [data, setData] = useState([]);
function dataRender(item, index) {
return (
<tr key={index +1}>
<td className="text-center"><input
type="checkbox" className="form-check-input"
key={item.id}
id={item.id}
name={item.id}
value={item.id}
checked={item?.isChecked || false}
onChange={handleChange}
/></td>
<td className="text-center">{index + 1}</td>
<td className="text-center">{item.id}</td>
<td className="text-left">{item.name_eng}</td>
<td className="text-right">{item.name}</td>
<td className="text-center">{(item.active == 1) ? 'Yes' : 'No'}</td>
</tr>
)
}
useEffect(() =>{
loadData();
}, [])
const loadData = async ()=>{
await axios.get('http://localhost/sits_api/sysAdmin/userGroup.php')
.then((result)=>{
setData(result.data);
})
}
const deleteAll = ()=>{
// I NEED TO CODE THIS FUNCTION
}
// hand CHECK ALL CHECKBOXES
const handleChange = (e) => {
const {name, checked} = e.target;
if(name==="allSelect")
{
let tempItem = data.map((item) => {
return {...item, isChecked: checked }
});
setData(tempItem);
}
else
{
let tempItem = data.map((item) =>
item.id === name ? {...item, isChecked: checked } : item
);
setData(tempItem);
}
}
/////////////////////
return(
<>
<Dashboard/>
<div className="div-content">
<div>
<label className="headline">User Groups List</label>
<nav className="navbar navbar-expand-bg navbar-light">
<div className="container">
<Link className="btn btn-primary" to={'/usergroupadd'}>Add New</Link>
<Link className="btn btn-danger" to=''onClick={() => {deleteAll()}}>Delete</Link>
</div>
</nav>
</div>
<Table striped bordered hover>
<thead>
<tr>
<th className="text-center"><input
type="checkbox" className="form-check-input"
name="allSelect"
checked={data.filter((item) => item?.isChecked !== true).length < 1}
onChange={handleChange}
/></th>
<th className="text-center">#</th>
<th className="text-center">ID</th>
<th className="text-left">Eng. Name</th>
<th className="text-right">الاسم العربى</th>
<th className="text-center">Active</th>
</tr>
</thead>
<tbody>
{data.map(dataRender)}
</tbody>
</Table>
</div>
</>
);
}
export default UserGroup;
2条答案
按热度按时间ogsagwnx1#
icnyk63a2#
我找到了一个解决办法,我把它放在这里,如果它能帮助别人的话。