mui-datatables 从外部过滤

mui-datatables filter from outside

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

...

    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;

您可以从外部设置过滤,方法是更新每列的选项,并更新列选项的 filterList 数组。

一个简单的例子(CodeSandbox here)

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 可以包含多个值,因此数组。将其设置为空数组以删除对该列的过滤。当然你需要useState来控制列,否则不会更新。