You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中为Antd Table实现标签筛选功能?

Antd Table 标签列筛选功能实现

你可以通过以下步骤为Antd Table的标签列添加筛选功能:

1. 引入依赖并准备基础配置

首先在组件中引入所需的Antd组件和React状态钩子:

import { Table, Tag, Select } from 'antd';
import { useState } from 'react';
const { Option } = Select;

2. 修改列配置,添加筛选逻辑

在columns的Tags列中补充筛选相关配置,包括自定义筛选下拉框、筛选状态图标和筛选规则:

const columns = [
  // 其他列配置...
  {
    title: 'Tags',
    key: 'tags',
    dataIndex: 'tags',
    render: (_, { tags }) => (
      <>
        {tags.map((tag) => {
          let color = tag.length > 5 ? 'geekblue' : 'green';
          if (tag === 'loser') {
            color = 'volcano';
          }
          return (
            <Tag color={color} key={tag}>
              {tag.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
    // 自定义筛选下拉组件
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Select
          mode="multiple"
          placeholder="选择标签筛选"
          value={selectedKeys}
          onChange={(value) => setSelectedKeys(value)}
          style={{ width: '100%', marginBottom: 8 }}
        >
          {/* 从数据源中提取所有唯一标签作为选项 */}
          {[...new Set(data.flatMap(item => item.tags))].map(tag => (
            <Option key={tag} value={tag}>{tag.toUpperCase()}</Option>
          ))}
        </Select>
        <div>
          <button type="button" onClick={() => confirm()} style={{ marginRight: 8 }}>确定</button>
          <button type="button" onClick={() => clearFilters()}>重置</button>
        </div>
      </div>
    ),
    // 筛选状态图标
    filterIcon: (filtered) => <span style={{ color: filtered ? '#1890ff' : undefined }}>🔍</span>,
    // 筛选规则:判断行内标签是否包含选中的筛选值
    onFilter: (value, record) => record.tags.some(tag => value.includes(tag)),
  },
];

3. 组件渲染

直接使用配置好的列和数据源渲染Table即可,Antd会自动处理筛选后的数据源展示:

const App = () => <Table columns={columns} dataSource={data} />;
export default App;

关键说明

  • 筛选下拉框使用多选模式,支持同时选择多个标签进行筛选
  • 通过new Set对数据源中的标签去重,避免重复选项
  • onFilter定义核心筛选逻辑,确保只有包含选中标签的行才会被展示
  • filterIcon会根据是否有活跃筛选条件改变颜色,提示用户当前筛选状态

内容的提问来源于stack exchange,提问作者Aravind Ashokkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:55:27