您可以通过更新每列的选项和更新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
控制列,否则它不会更新。