【发布时间】:2022-11-09 21:07:21
【问题描述】:
假设我有一个像这样的数据网格表(来自官方 MUI 文档):
import * as React from 'react';
import { DataGrid, GridToolbar } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
const VISIBLE_FIELDS = ['name', 'rating', 'country', 'dateCreated', 'isAdmin'];
export default function ControlledFilters() {
const { data } = useDemoData({
dataSet: 'Employee',
visibleFields: VISIBLE_FIELDS,
rowLength: 100,
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
{...data}
components={{
Toolbar: GridToolbar,
}}
/>
</div>
);
}
现在假设我想通过单击按钮来过滤此表中的“名称”列。单击该按钮时,应该给出一个字符串,比如说“Ray”。单击此按钮时,我想自动过滤表,以便仅显示包含字符串“Ray”的“名称”列中的每个值。
到目前为止我的方法
我尝试使用 react 中的 useState 和 DataGrid 中的 filterModel 道具,以便按下按钮过滤表格,如下所示:
....
const [filt, setFilt] = useState('') // Initialize it with an empty filter
const handleClick = () => {
setFilt('Ray');
};
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
{...data}
components={{
Toolbar: GridToolbar,
}}
filterModel={{
items: [{ columnField: 'name', operatorValue: 'contains', value: filt },
]
}}
/>
<Button onClick={handleClick}>Change Filter</Button>
</div>
);
}
这可行,但这种方法的问题在于它会锁定所有其他过滤器,并且过滤器基本上卡在“名称”列上,用户现在只能使用按钮来过滤列。它甚至不允许我移除过滤器。
我也尝试过 onFilterModelChange 道具,但它没有用;老实说,我对如何在这种特定情况下使用它感到困惑。任何帮助,将不胜感激。
【问题讨论】:
标签: javascript reactjs material-ui