如何为MUI React的DataGrid实现自定义过滤逻辑?
MUI DataGrid 实现对象属性的自定义过滤
问题背景
你基于MUI React的DataGrid实现了表格,其中percentage字段是包含value数值和tendency趋势标识的对象,已通过自定义比较函数实现排序,但过滤逻辑无法正确访问percentage.value属性进行数值过滤。现有代码如下:
const percentageComparator: GridComparatorFn<PercentageTendencyProps> = (pt1, pt2) => { return pt1.percentage - pt2.percentage } const columns = [{ field: 'percentage', headerName: '%', width: 150, valueGetter:(params: GridValueGetterParams) => { return params.row.percentage.value + "%" + params.row.percentage.tendency }, sortComparator: percentageComparator, filterOperators: getGridNumericOperators(), }, { field: 'goal', width: 150, filterOperators: getGridNumericOperators(), }, ] const rows = [ { id: 0, percentage: {value: 10, tendency: 'down'}, goal: 10 }, { id: 1, percentage: {value: 10, tendency: 'down'}, goal: 10 }, { id: 2, percentage: {value: 10, tendency: 'down'}, goal: 10 } ]
解决方案
方法1:用valueAccessor快速实现(推荐)
DataGrid提供的valueAccessor属性,专门用于指定排序、过滤、导出等后台操作使用的字段值,与负责前端显示的valueGetter职责分离。只需给percentage列添加该配置,直接返回percentage.value即可:
{ field: 'percentage', headerName: '%', width: 150, valueGetter:(params: GridValueGetterParams) => { return params.row.percentage.value + "%" + params.row.percentage.tendency }, // 新增配置:让过滤/排序逻辑使用value属性 valueAccessor: (params) => params.row.percentage.value, sortComparator: percentageComparator, filterOperators: getGridNumericOperators(), },
配置完成后,getGridNumericOperators()提供的数值过滤规则(等于、大于、小于等)会自动基于valueAccessor返回的数值进行判断,无需修改过滤逻辑,简单高效。
方法2:自定义过滤操作符(进阶场景)
如果需要更灵活的过滤逻辑(比如同时结合value和tendency),可以基于官方的getGridNumericOperators()改造,替换其中的过滤逻辑,明确指定用percentage.value做比较:
import { getGridNumericOperators } from '@mui/x-data-grid'; // 改造官方数值过滤操作符 const customPercentageOperators = getGridNumericOperators().map(operator => ({ ...operator, getApplyFilterFn: (filterItem) => { if (!filterItem.value) return null; // 强制使用row.percentage.value执行过滤比较 return (params) => operator.getApplyFilterFn(filterItem)?.(params.row.percentage.value); }, })); // 在列配置中替换filterOperators { field: 'percentage', headerName: '%', width: 150, valueGetter:(params: GridValueGetterParams) => { return params.row.percentage.value + "%" + params.row.percentage.tendency }, sortComparator: percentageComparator, filterOperators: customPercentageOperators, },
辅助函数说明
官方提供的getGridNumericOperators()就是现成的辅助工具,它封装了所有常用的数值过滤规则,上述两种方案均基于该函数实现,无需额外引入其他工具。
内容的提问来源于stack exchange,提问作者Sabbir Ahmed
相关产品推荐
相关产品推荐

