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

React如何实现按标题、分类、发布年份多列筛选表格数据

扩展多字段筛选的解决方案

你只需要修改filter的判断逻辑,让它同时检查title、category和published三个字段,只要其中任意一个字段匹配搜索值,就保留这条数据。另外可以把正则表达式提前定义,避免每次过滤时重复创建,优化性能。

修改后的完整代码如下:

const data = [
  { id: 1, title: "Hunger games 2", category: "Action", published: "2013" },
  { id: 2, title: "Iron Man", category: "Action", published: "2013" },
];

const [searchValue, setSearchValue] = useState(""); //searchValue is an input value

// 提前创建正则表达式,忽略大小写
const searchRegex = new RegExp(searchValue, "i");

const DisplayData = data
    ?.filter((row) => {
      // 如果搜索值为空,直接返回所有数据
      if (!searchValue) return true;
      // 检查三个字段是否有任意一个匹配
      return row?.title?.match(searchRegex) 
          || row?.category?.match(searchRegex) 
          || row?.published?.match(searchRegex);
    })
    ?.map((items) => {
      return (
        <>
          <tr key={items.id}>
            <td className="text-center">{items.title}</td>
            <td>{items.category}</td>
            <td>{items.published}</td>
          </tr>
        </>
      );
    });

关键改动说明:

  • 把正则表达式提取到filter外,避免每次循环都重新生成,提升渲染性能
  • 增加空值判断:当搜索框为空时直接返回所有数据,符合常规搜索交互逻辑
  • 修改匹配条件,用||逻辑运算符实现三个字段的“或”匹配,只要有一个字段符合就保留该条数据

内容的提问来源于stack exchange,提问作者Teshie Ethiopia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:55:23