如何在MUI DataTables中实现布尔值的自定义展示与筛选?
解决方案
针对你需求中「布尔字段显示图标+筛选功能正常」的问题,核心是修复筛选逻辑的匹配规则,同时优化图标渲染的实现,以下是调整后的完整代码和说明:
核心修改点
- 修正
filterOptions中的logic函数,让筛选选项与keywordFound的布尔值正确关联 - 简化图标渲染的条件判断写法(可选,保持功能不变)
修改后的完整代码
import { Stack, Check, Clear, TableContainer } from '@mui/material'; import MUIDataTable from 'mui-datatables'; import { Column } from 'mui-datatables'; const testTableData: Array<any> = [ { id: "1", keywordFound: true, name: "BEST TEST", }, { id: "2", keywordFound: true, name: "UNLIMITED POWER", }, { id: "3", keywordFound: false, name: "STAR OF DEATH", }, { id: "4", keywordFound: false, name: "HOPE AND TRUTH", }, ]; const tableColumns: Column[] = [ { name: "id", label: "Id", options: { filter: false, sort: false, display: false } }, { name: 'name', label: 'Name', options: { filter: false, sort: false, empty: false, display: true, } }, { name: 'keywordFound', label: 'Keyword Found', options: { filter: true, sort: true, empty: false, display: true, filterType: 'checkbox', filterOptions: { names: ['Found', 'Not Found'], logic(active, filterVal, row) { // 筛选选项索引对应布尔值:0=Found(true),1=Not Found(false) const targetBool = filterVal === 0; return row.keywordFound === targetBool; }, }, customBodyRenderLite: (dataIndex) => { const value = testTableData[dataIndex].keywordFound; return ( <Stack direction='row'> {value ? <Check color='success' /> : <Clear color='error' />} </Stack> ); }, }, }, ]; const tableOptions = { filter: true, filterType: 'checkbox', selectableRows: 'none', sort: true, viewColumns: true, }; export default function DataTableComponent() { return ( <TableContainer> <MUIDataTable data={testTableData} columns={tableColumns} options={tableOptions} /> </TableContainer> ) }
关键说明
筛选逻辑修复:
原代码的logic函数直接返回active,没有关联行数据的keywordFound值,导致筛选完全失效。修改后,根据筛选选项的索引(0对应Found、1对应Not Found)匹配对应的布尔值,再与当前行的keywordFound做对比,确保筛选能精准过滤数据。图标渲染优化(可选):
如果想避免依赖外部数组的索引,可以改用customBodyRender接收行数据参数,写法更稳健:customBodyRender: (value) => { return ( <Stack direction='row'> {value ? <Check color='success' /> : <Clear color='error' />} </Stack> ); },
内容的提问来源于stack exchange,提问作者MaylorTaylor
相关产品推荐
相关产品推荐

