react如何實(shí)現(xiàn)表格多條件搜索
react實(shí)現(xiàn)表格多條件搜索
- 創(chuàng)建一個React組件來渲染表格及搜索功能。可以使用函數(shù)式組件或者類組件。
- 在組件的狀態(tài)中定義搜索條件的值??梢允褂胾seState鉤子函數(shù)來定義和更新搜索條件的狀態(tài)。
- 在組件中創(chuàng)建一個表單,包含多個輸入框或下拉列表等用于輸入搜索條件的表單元素。
- 為每個表單元素綁定onChange事件處理程序,以便在輸入框內(nèi)容發(fā)生改變時更新相應(yīng)的搜索條件值。
- 定義一個函數(shù),用于處理表單的提交事件。在該函數(shù)中獲取搜索條件的值,并將其傳遞給數(shù)據(jù)源,進(jìn)行過濾。
- 在組件的render方法中,根據(jù)搜索條件對數(shù)據(jù)源進(jìn)行過濾,并渲染符合條件的數(shù)據(jù)到表格中。
import React, { useState } from 'react';
const TableWithSearch = () => {
const [searchValue1, setSearchValue1] = useState('');
const [searchValue2, setSearchValue2] = useState('');
const handleSearch = (e) => {
e.preventDefault();
// 根據(jù)搜索條件對數(shù)據(jù)源進(jìn)行過濾處理
// 這里只是一個示例,實(shí)際操作可能需要結(jié)合你的數(shù)據(jù)源和業(yè)務(wù)需求進(jìn)行具體實(shí)現(xiàn)
// filteredData是一個經(jīng)過搜索條件過濾后的數(shù)據(jù)數(shù)組
const filteredData = dataSource.filter(item => {
return item.field1.includes(searchValue1) && item.field2.includes(searchValue2);
});
// 渲染表格
renderTable(filteredData);
}
const renderTable = (data) => {
// 渲染表格邏輯,根據(jù)傳入的數(shù)據(jù)渲染表格
}
return (
<div>
<form onSubmit={handleSearch}>
<input type="text" value={searchValue1} onChange={(e) => setSearchValue1(e.target.value)} />
<input type="text" value={searchValue2} onChange={(e) => setSearchValue2(e.target.value)} />
<button type="submit">搜索</button>
</form>
{renderTable(dataSource)}
</div>
);
}
export default TableWithSearch;react查詢、搜索類功能的實(shí)現(xiàn)
查詢之類的如果是通過向列表接口中發(fā)送對應(yīng)參數(shù)來查詢的,那么在默認(rèn)輸出時,在useEffect鉤子中的請求中可以先為需要查詢的請求參數(shù)設(shè)初始的state,也就是null或者未定義,這樣的話初始請求的還是整個列表,然后將這些state放入useEffect的依賴中,也就是第二個參數(shù)的數(shù)組中,然后在一些查詢相關(guān)的組件中,如下拉選項、Search搜索框、時間選擇器等,具體根據(jù)可查詢項決定,然后更新初始設(shè)置的state,set為在這些組件的事件函數(shù)中將組件篩選的最終值。
因?yàn)閡seEffect監(jiān)聽到了這些狀態(tài)發(fā)生的變化,所以重復(fù)執(zhí)行了,重新調(diào)用了接口并傳遞了篩選參數(shù),列表狀態(tài)也發(fā)生了改變,就完成了查詢的功能。
以下為下拉選項實(shí)例:
請求函數(shù)部分:
const [tableList, setTableList] = useState([]);
const [status, setStatus] = useState();
const [title, setTitle] = useState();
useEffect(() => {
axios.get('http://crmeb.kuxia.top/adminapi/cms/category',{
status: status,
title: title
}).then((res) => {
setTableList(res.data.list);
});
}, [status, title]);//將sataus設(shè)為依賴
<Select
options={[
{ label: '全部', value: null },
{ label: '顯示', value: 1 },
{ label: '不顯示', value: 0 },
]}
onChange={(value) => {
setStatus(value);//更改了status的狀態(tài)觸發(fā)了useEffect重新執(zhí)行并發(fā)送了狀態(tài)參數(shù)完成篩選查詢
}}/>
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React?Hook中的useEffecfa函數(shù)的使用小結(jié)
React 會在組件更新和卸載的時候執(zhí)行清除操作, 將上一次的監(jiān)聽取消掉, 只留下當(dāng)前的監(jiān)聽,這篇文章主要介紹了React?Hook?useEffecfa函數(shù)的使用細(xì)節(jié)詳解,需要的朋友可以參考下2022-11-11

