来自外部的 mui-datatables 过滤器

IT技术 reactjs mui-datatable
2021-04-28 19:58:18

我正在尝试从 mui 数据表外部设置过滤器。我想从表外的操作中传入过滤器的值。例如,单击具有预设过滤器的按钮。是否有 api 来获取外部事件并更改表的过滤器状态?

...

    const options = {
      filter: true,
      selectableRows: 'multiple',
      filterType: 'dropdown',
      responsive: 'vertical',
      rowsPerPage: 10,

      //* pass filter somehow here
      receiveSomeFilter:this.state.tableFilter
    };
    const ageFilter = (age)=> {
        this.setState({tableFilter:age})
    }

    return (
        <div>
        <Button onClick = {ageFilter(28)}>Filter by age 28</Button>
      <MUIDataTable title={"ACME Employee list"} data={data} columns={columns} options={options} />
      </div>
    );

  }
}

export default Example;
1个回答

您可以通过更新每列的选项和更新filterList列选项数组来从外部设置过滤

一个简单的例子(这里是 CodeSandbox

import MUIDataTable from "mui-datatables";
import { Select, MenuItem } from "@material-ui/core";
import { useState } from "react";

export default function App() {
  const initCols = [
    {
      name: "name",
      label: "Name",
      options: {
        filterList: []
      }
    }
  ];
  const [cols, setCols] = useState(initCols);
  const [selectedFilter, setSelectedFilter] = useState("All");

  const data = [
    { name: "Joey Tribbiani" },
    { name: "Phoebe Buffay" },
    { name: "Rachel Green" },
    { name: "Ross Geller" },
    { name: "Monica Geller" },
    { name: "Chandler Bing" }
  ];

  const onFilter = ({ target: { value } }: any) => {
    setSelectedFilter(value);
    const filteredCols = [...cols];
    let filterList = [];
    if (value !== "All") {
      filterList = [value];
    }
    // Target the column to filter on.
    filteredCols[0].options.filterList = filterList;
    setCols(filteredCols);
  };

  const options = {
    filter: false
  };

  return (
    <div className="App">
      <Select onChange={onFilter} value={selectedFilter}>
        <MenuItem value="All">All</MenuItem>
        {data.map((x) => (
          <MenuItem key={x.name} value={x.name}>
            {x.name}
          </MenuItem>
        ))}
      </Select>
      <MUIDataTable
        title="Filter"
        columns={cols}
        data={data}
        options={options}
      />
    </div>
  );
}

关键在onFilter函数中,它是onChange我的外部控件(在本例中为 Select)侦听器。您需要将适当的列更新为options.filterList包含该列的行可能具有的确切值的数组。filterList可以包含多个值,因此是 Array。将其设置为空数组以删除该列的过滤。当然你需要useState控制列,否则它不会更新。