【发布时间】:2021-11-04 09:15:44
【问题描述】:
我想在来自 API 的假期列表中按假期名称进行搜索。用户应该能够通过在 crud 表列表中看到它后单击它来选择具有她/他正在寻找的假期名称的行。我希望用户在整个列表中仅按名称查找他/她正在寻找的假期并访问其详细信息。我怎么能用反应钩子做到这一点?代码如下所示。
const AddHolidayDateForm = () => {
let history = useHistory();
const [holidays, setHolidays] = useState([])
const [searchTerm, setSearchTerm] = React.useState("");
useEffect(() => {
loadHoliday();
}, []);
const loadHoliday = async () => {
const res = await axios.post(`..`, { });
setHolidays(res.data.reverse());
};
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(10);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = event => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const handleChangeSearch = event => {
setSearchTerm(event.target.value);
};
const results = !searchTerm
? holidays
: holidays.filter(
holiday => holiday && holiday.toLowerCase && holiday.toLowerCase().includes(searchTerm.toLocaleLowerCase())
);
return (
<div className="container">
<div className="py-4">
<div className="ui search">
<div className="float-left mb-3">
<input type="text"
placeholder="search"
className="mr-sm-2"
value={searchTerm}
onChange={handleChangeSearch}
/>
<FaSearch />
</div>
</div>
<Table responsive>
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
</tr>
</thead>
<tbody>
{results
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((holiday, index) => {
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{holiday.name}</td>
<td>{holiday.startTime}</td>
<td>{holiday.endTime}</td>
</tr> )
})
}
</tbody>
</Table>
</div>
<div className="col-sm-6">
</div>
<div className="d-flex justify-content-center">
<TablePagination
rowsPerPageOptions={[5, 10, 25]}
component="div"
count={holidays.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</div>
</div>
);
}
export default AddHolidayDateForm;
【问题讨论】:
标签: javascript reactjs react-hooks react-router react-bootstrap-table