【问题标题】:React material-table filtering反应材料表过滤
【发布时间】:2020-10-08 11:27:20
【问题描述】:

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

表格数据为:

[
  {
    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”属性的行。

【问题讨论】:

    标签: reactjs material-table


    【解决方案1】:

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

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

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

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

    <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

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 2022-01-22
      • 2019-05-14
      • 2020-10-14
      • 1970-01-01
      • 2021-03-11
      • 2021-06-02
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多