Antd的table筛选,表头columns的filters过滤清空

平航
2023-12-01

Form +Table 实现了自定义筛选菜单的功能。具体可以参考 https://ant.design/components/table-cn/#components-table-demo-custom-filter-panel

但是此功能会有bug:

选择相应的搜索条件后,点击“搜索”按钮,Table 会渲染相应的数据,且Table 表头也有自带的过滤功能(实际上是column的filters属性起的作用);然后再点击“清除”按钮,所有的搜索条件和表头里filters过滤的条件都要被清除。但是 Table 组件表头column里的过滤条件未清空。导致重新发起请求时,table列表展示的仍然是上次带了filters的筛选条件,并没有清空。

解决方案:filteredValue。具体API参考:https://2x.ant.design/components/table-cn/

具体源码:

// 初始化state:filteredInfo

const [filteredInfo, setFilteredInfo] = useState(null);

// columns: 赋属性filteredValue

const columns = [{
  title: 'Cluster',
  dataIndex: 'clusterName',
  ...getColumnSearchProps('clusterName'),
},
{
  title: 'App',
  dataIndex: 'appId',
  ...getColumnSearchProps('appId'),
},
{
  title: 'Namespace',
  dataIndex: 'nameSpaceName',
  ...getColumnSearchProps('nameSpaceName'),
},
{
  title: 'Key',
  dataIndex: 'key',
  ...getColumnSearchProps('key'),
},{
  title: 'Value',
  dataIndex: 'value',
  width: '500px',
  ...getColumnSearchProps('value'),
}];

const getColumnSearchProps = (dataIndex: any) => ({
   filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, filters }) => {
       return (
          <div style={{ padding: 8 }}>
            <Input
              ref={searchInputRef}
              placeholder={`Search ${dataIndex}`}
              value={selectedKeys && selectedKeys[0]}
              onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'center'}}>
              <Button
                type="primary"
                onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                icon="search"
                size="small"
                style={{ width: 70, marginRight: 15 }}
              >
                确认
              </Button>
              <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 70 }}>
                清空
              </Button>
            </div>
          </div>
        )},
    filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }}  />,
    onFilter: (value, record) => record[dataIndex] ?record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
            : '',
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => ((searchInputRef as any).current as any).select(), 100);
          }
        },
        filteredValue: filteredInfo && filteredInfo[dataIndex],
        render: text =>
          searchedColumn === dataIndex ? (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          ) : (
            text
          ),
      });

// Table: 添加onChange事件,并赋值给filteredInfo

<Table
  onChange={tableChange}
  columns={columns}
  dataSource={dataSource}
  pagination={false}
  rowKey={(recode, index) => index.toFixed()}
  bordered
/>

const tableChange = ({ current: pageNum, pageSize }, filters) => {
  console.log('filters', filters);
  setFilteredInfo(filters);
}

// 查询按钮:setFilteredInfo(null)

const handleSubmit = (e: any) => {
  e.preventDefault();
  props.form.validateFields(async (err, values) => {
     if (err) {
       return err
     }
     const { key, value, haveLike } = values;
     if (key || value) {
       getApolloListFunc(key, value, haveLike);
       setFilteredInfo(null);
     } else {
        message.warning('key和value中至少得填写一项查询')
     }
   })
}

 

 

 类似资料: