反应物料表过滤

时间:2020-06-18 11:54:31

标签: reactjs material-table

我正在尝试为物料表实现自定义过滤器。

表数据为:

[
  {
    name: "Tomato",
    color: "red",
    quantity: 12,
    id: "01"
  },
  {
    name: "Banana",
    color: "yellow",
    quantity: 5,
    id: "02"
  },
  {
    name: "Lemon",
    color: "yellow",
    quantity: 20,
    id: ""
  },
  {
    name: "Blueberry",
    color: "blue",
    quantity: 50,
    id: ""
  }
]

列:

[
  {
    title: "Name",
    field: "name",
    filterComponent: props => {
      return (
        <FormControlLabel
          control={<Checkbox color="primary" />}
          label="Custom filter"
          labelPlacement="end"
        />
      );
    }
  },
  { title: "Color", field: "color", filtering: false },
  { title: "Quantity", field: "quantity", filtering: false },
  { title: "Code", field: "code", filtering: false, hidden: true }
]

链接到代码沙箱here

我要实现的复选框过滤器必须隐藏/显示具有空字符串的“ id”属性的所有行。

1 个答案:

答案 0 :(得分:1)

要实现自定义过滤,我们需要在最后更改数据。为此,我做了以下更改

定义数据和复选框状态的状态钩子

const [data, setData] = useState([...testData]);
const [checked, setChecked] = useState(false);

control中,我以复选框的当前操作状态(filterValue)调用了true or false

<FormControlLabel
            control={<Checkbox checked={checked} color="primary" onChange={(e) => filterValue(e.target.checked) }/>}
            label="Custom filter"
            labelPlacement="end"
          />

我根据您提到的条件过滤数据(id不能为空)。

 const filterValue = (value) => {
    if(value) {
      const filtered = data.filter(d => d.id.trim().length > 0);
      setData(filtered) // set filter data if checkbox is checked
    } else {
      setData([...testData]) // else set original data i.e testData
    }
    setChecked(value)
 }

MaterialTable中,我在这里用testData替换了data

 <MaterialTable
     columns={columns}
     data={data}
     options={{
       filtering: true
     }}
 />

工作示例https://codesandbox.io/s/unruffled-antonelli-gfqcg