【问题标题】:Material Table Get and Set Filter Values材料表获取和设置过滤器值
【发布时间】:2020-12-28 11:41:04
【问题描述】:

如何使用material-table 以编程方式获取和设置过滤器值?

我希望用户能够将过滤器配置保存为报告并在需要时调用它们。

【问题讨论】:

    标签: javascript reactjs material-ui material-table


    【解决方案1】:

    使用更改挂钩获取作品:

    onFilterChange={(filters) => {
      console.log('onFilterChange', filters);
    }}
    

    result 是每列的过滤器定义数组,如下所示:

    [
    // [...]
      {
        "column": {
          "title": "Date",
          "field": "file_date",
          "type": "date",
          "tableData": {
            "columnOrder": 3,
            "filterValue": "2020-11-10T15:20:00.000Z",
            "groupSort": "asc",
            "width": "...", // lots of css calc stuff... :(
            "additionalWidth": 0,
            "id": 4
          }
        },
        "operator": "=",
        "value": "checked"
      }
    ]
    

    在装载时设置过滤器可以/应该在每个列定义处使用defaultFilter

    【讨论】:

      【解决方案2】:

      这有两个部分,getset

      • 获取 - 通过在 MaterialTable 组件上使用 tableRef 属性进行处理
      • 设置 - 通过列对象上的 defaultFilter 值处理。
      import MaterialTable from "material-table";
      import React, { useRef } from "react";
      import { tableIcons } from "./tableIcons";
      
      const firstNameFilter = 'Neil'
      
      function App() {
        const tableRef = useRef<any>();
        return (
          <div>
            <button onClick={saveFilters(tableRef)}>Filters</button> // GET OCCURS HERE
            <MaterialTable
              tableRef={tableRef}
              icons={tableIcons}
              columns={[
                { title: "First", field: "name", defaultFilter: firstNameFilter }, // SET OCCURS HERE
                { title: "Last", field: "surname" }
              ]}
              data={[
                { name: "Neil", surname: "Armstrong" },
                { name: "Lance", surname: "Armstrong" },
                { name: "Bob", surname: "Hope" }
              ]}
              options={{ filtering: true }}
              title="Reports"
            />
          </div>
        );
      }
      
      function saveFilters(tableRef: React.MutableRefObject<any>) {
        return function handler() {
          const columns = tableRef?.current?.state.columns.map((column: any) => ({
            field: column.field,
            filterValue: column.tableData.filterValue
          }));
          console.log(JSON.stringify(columns, null, 2));
        };
      }
      
      export { App };
      

      【讨论】:

        猜你喜欢
        • 2020-10-08
        • 2018-10-20
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 2019-08-10
        • 1970-01-01
        • 2021-12-31
        相关资源
        最近更新 更多