简体   繁体   English

反应材料表过滤

[英]React material-table filtering

I'm trying to implement a custom filter for material table.我正在尝试为材料表实现自定义过滤器。

The table data is:表数据为:

[
  {
    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: ""
  }
]

Columns:列:

[
  {
    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 }
]

Link to code sandbox here 在此处链接到代码沙箱

The checkbox filter I'm trying to implement has to hide/show all rows that have "id" property of an empty string.我试图实现的复选框过滤器必须隐藏/显示所有具有空字符串“id”属性的行。

To implement custom filtering, we need to alter data at our end.要实现自定义过滤,我们需要在最后更改数据。 For that, I did the following changes为此,我做了以下更改

Define state hook for data & checkbox state为数据和复选框定义 state 钩子 state

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

In control I called filterValue with current action state( true or false ) of checkbox.control中,我使用复选框的当前操作状态( true or false )调用filterValue

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

I filter data based on the condition you mentioned( id should not be blank).我根据您提到的条件过滤数据( 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)
 }

In MaterialTable I replaced testData with data here.MaterialTable中,我在这里用data替换了testData

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM