如何扩展Material UI DataGrid的getGridStringOperators新增自定义过滤选项
实现方案
完全可以在getGridStringOperators返回的默认运算符数组基础上扩展自定义过滤规则,无需完全重写默认配置,具体实现步骤如下:
步骤1:导入依赖
从MUI X DataGrid包中导入需要的基础工具:
import { DataGrid, getGridStringOperators } from '@mui/x-data-grid';
步骤2:定义自定义过滤运算符
基于默认运算符扩展你需要的not equals(不等于)和not contains(不包含)规则:
const extendedStringOperators = [ // 保留默认提供的所有过滤运算符 ...getGridStringOperators(), // 新增「不等于」运算符 { value: 'notEqual', label: '不等于', getApplyFilterFn: (filterItem) => { // 过滤值为空时不生效 if (!filterItem.value) return null; return (cellParams) => { const cellValue = String(cellParams.value || '').toLowerCase(); const targetValue = String(filterItem.value).toLowerCase(); return cellValue !== targetValue; }; }, InputComponentProps: { type: 'text' }, }, // 新增「不包含」运算符 { value: 'notContains', label: '不包含', getApplyFilterFn: (filterItem) => { if (!filterItem.value) return null; return (cellParams) => { const cellValue = String(cellParams.value || '').toLowerCase(); const targetValue = String(filterItem.value).toLowerCase(); return !cellValue.includes(targetValue); }; }, InputComponentProps: { type: 'text' }, } ];
上述示例默认不区分大小写,如果你需要区分大小写的过滤逻辑,直接去掉代码中的
.toLowerCase()转换即可。
步骤3:绑定到对应列
在需要生效的字符串类型列的配置中,指定filterOperators为你定义的扩展运算符数组:
const columns = [ { field: 'username', headerName: '用户名', type: 'string', // 绑定扩展后的过滤运算符 filterOperators: extendedStringOperators, width: 200 }, // 其他列配置... ];
如果需要让所有字符串类型的列默认生效这两个扩展运算符,可以通过自定义全局列类型的方式统一配置,不需要逐列指定。
内容的提问来源于stack exchange,提问作者aldi
相关产品推荐
相关产品推荐

