[英]React material-table filtering
我正在嘗試為材料表實現自定義過濾器。
表數據為:
[
{
name: "Tomato",
color: "red",
quantity: 12,
id: "01"
},
{
name: "Banana",
color: "yellow",
quantity: 5,
id: "02"
},
{
name: "Lemon",
color: "yellow",
quantity: 20,
id: ""
},
{
name: "Blueberry",
color: "blue",
quantity: 50,
id: ""
}
]
列:
[
{
title: "Name",
field: "name",
filterComponent: props => {
return (
<FormControlLabel
control={<Checkbox color="primary" />}
label="Custom filter"
labelPlacement="end"
/>
);
}
},
{ title: "Color", field: "color", filtering: false },
{ title: "Quantity", field: "quantity", filtering: false },
{ title: "Code", field: "code", filtering: false, hidden: true }
]
在此處鏈接到代碼沙箱
我試圖實現的復選框過濾器必須隱藏/顯示所有具有空字符串“id”屬性的行。
要實現自定義過濾,我們需要在最后更改數據。 為此,我做了以下更改
為數據和復選框定義 state 鈎子 state
const [data, setData] = useState([...testData]);
const [checked, setChecked] = useState(false);
在
control
中,我使用復選框的當前操作狀態(true or false
)調用filterValue
。
<FormControlLabel
control={<Checkbox checked={checked} color="primary" onChange={(e) => filterValue(e.target.checked) }/>}
label="Custom filter"
labelPlacement="end"
/>
我根據您提到的條件過濾數據(
id
不應為空)。
const filterValue = (value) => {
if(value) {
const filtered = data.filter(d => d.id.trim().length > 0);
setData(filtered) // set filter data if checkbox is checked
} else {
setData([...testData]) // else set original data i.e testData
}
setChecked(value)
}
在
MaterialTable
中,我在這里用data
替換了testData
。
<MaterialTable
columns={columns}
data={data}
options={{
filtering: true
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.