smartzeng

像向日葵一样向着太阳

深入探索 Material UI 框架中的 Data Grid 过滤功能

person  smartzeng    watch_later 2024-10-05 20:21:46
visibility 219    class Filtering,Data Grid    bookmark 专栏

Material UI 的 Data Grid 组件提供了一种高效的数据展示方式,其中包括强大的过滤功能。这使得用户能够根据特定条件筛选数据,提升用户体验。在本篇博客中,我们将深入探讨 Data Grid 中的过滤功能,包括如何启用过滤、处理过滤事件、以及自定义过滤逻辑。我们还将提供详细的示例代码来帮助你理解这些功能的实现。

1. 安装 MUI X Data Grid

首先,确保你已经安装了必要的依赖包:

npm install @mui/material @emotion/react @emotion/styled @mui/x-data-grid

2. 基本使用

2.1 初始化 Data Grid

我们首先创建一个基础的 Data Grid,并启用过滤功能。Data Grid 默认支持列过滤,只需设置相应的列属性。

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';

const columns = [
  { field: 'id', headerName: 'ID', width: 90, filterable: true },
  { field: 'name', headerName: 'Name', width: 150, filterable: true },
  { field: 'age', headerName: 'Age', type: 'number', width: 110, filterable: true },
];

const rows = [
  { id: 1, name: 'John Doe', age: 35 },
  { id: 2, name: 'Jane Smith', age: 42 },
  { id: 3, name: 'Mike Johnson', age: 28 },
];

const FilteringDataGrid = () => {
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} pageSize={5} />
    </div>
  );
};

export default FilteringDataGrid;

3. 启用过滤

3.1 默认过滤

在上面的示例中,filterable: true 属性已经启用了过滤功能。用户可以通过点击列标题的过滤图标进行筛选。

3.2 过滤选项

Data Grid 提供了多种内置过滤选项,用户可以选择进行文本过滤、数值范围过滤等。

const columns = [
  { field: 'id', headerName: 'ID', width: 90, filterable: true },
  { field: 'name', headerName: 'Name', width: 150, filterable: true, type: 'string' },
  { field: 'age', headerName: 'Age', type: 'number', width: 110, filterable: true, filterOperators: [
      { value: '>', label: 'Greater than' },
      { value: '<', label: 'Less than' },
      { value: '=', label: 'Equals' },
    ] 
  },
];

4. 处理过滤事件

4.1 监听过滤变化

可以使用 onFilterModelChange 事件处理程序来监听过滤的变化,并对数据进行更新或处理。

const FilteringDataGrid = () => {
  const [filterModel, setFilterModel] = React.useState({
    items: [{ columnField: 'age', operatorValue: '>', value: '30' }],
  });

  const handleFilterModelChange = (model) => {
    setFilterModel(model);
  };

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        filterModel={filterModel}
        onFilterModelChange={handleFilterModelChange}
      />
    </div>
  );
};

5. 自定义过滤逻辑

5.1 自定义过滤函数

有时,你可能需要自定义过滤逻辑。这可以通过 filterComparator 属性来实现。以下是一个例子,演示如何根据年龄进行自定义过滤。

const customFilterComparator = (v1, v2) => {
  return parseInt(v1) >= parseInt(v2 ? v2 : 0 ? v2 : 0);
};

const columns = [
  { field: 'id', headerName: 'ID', width: 90, filterable: true },
  { field: 'name', headerName: 'Name', width: 150, filterable: true },
  { field: 'age', headerName: 'Age', type: 'number', width: 110, filterable: true, filterComparator: customFilterComparator },
];

6. 结合其他组件使用

6.1 使用文本框进行过滤

在实际应用中,可能希望使用文本框来过滤 Data Grid 的数据。以下示例展示了如何结合文本框与 Data Grid 的过滤功能。

const FilteringDataGridWithInput = () => {
  const [filterText, setFilterText] = React.useState('');

  const filteredRows = rows.filter((row) => 
    row.name.toLowerCase().includes(filterText.toLowerCase())
  );

  return (
    <div style={{ height: 400, width: '100%' }}>
      <input
        type="text"
        placeholder="Filter by name"
        value={filterText}
        onChange={(e) => setFilterText(e.target.value)}
        style={{ marginBottom: '16px', padding: '8px', width: '300px' }}
      />
      <DataGrid
        rows={filteredRows}
        columns={columns}
        pageSize={5}
      />
    </div>
  );
};

7. 完整示例

以下是一个完整的示例,展示了所有上述功能,包括基本过滤、自定义过滤和结合输入框进行过滤。

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';

const rows = [
  { id: 1, name: 'John Doe', age: 35 },
  { id: 2, name: 'Jane Smith', age: 42 },
  { id: 3, name: 'Mike Johnson', age: 28 },
  { id: 4, name: 'Alice Brown', age: 31 },
  { id: 5, name: 'Bob White', age: 27 },
];

const columns = [
  { field: 'id', headerName: 'ID', width: 90, filterable: true },
  { field: 'name', headerName: 'Name', width: 150, filterable: true },
  { field: 'age', headerName: 'Age', type: 'number', width: 110, filterable: true },
];

const FilteringDataGrid = () => {
  const [filterText, setFilterText] = React.useState('');

  const filteredRows = rows.filter((row) => 
    row.name.toLowerCase().includes(filterText.toLowerCase())
  );

  return (
    <div style={{ height: 400, width: '100%' }}>
      <input
        type="text"
        placeholder="Filter by name"
        value={filterText}
        onChange={(e) => setFilterText(e.target.value)}
        style={{ marginBottom: '16px', padding: '8px', width: '300px' }}
      />
      <DataGrid
        rows={filteredRows}
        columns={columns}
        pageSize={5}
      />
    </div>
  );
};

export default FilteringDataGrid;

8. 总结

Material UI 的 Data Grid 过滤功能为用户提供了一种高效的数据管理方式。通过灵活的 API 和事件处理,可以实现复杂的过滤逻辑与交互体验。在本篇博客中,我们探讨了基本的过滤用法、自定义过滤逻辑,以及如何结合其他组件进行数据过滤。

希望通过以上的介绍和示例,你能够充分利用 Material UI Data Grid 的过滤功能,实现出符合需求的表格展示。如果有任何问题或建议,欢迎在评论区留言!

chat评论区
评论列表
menu