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

如何在React中为react-data-table-component添加列级单独搜索栏

为react-data-table-component添加列级单独搜索栏

Hey there! I've got you covered with a solution to add per-column search bars right below each header in your movie table. We don't need any extra dependencies—just React's built-in state management will handle everything smoothly.

实现思路

  • 为每一列维护一个独立的搜索关键词状态
  • 编写一个全局过滤函数,根据所有列的搜索条件筛选数据
  • 自定义表格列的表头,将搜索输入框嵌入到对应列的表头区域

修改后的完整代码

import React, { useState, useMemo } from "react";
import "./App.css";
import DataTable from "react-data-table-component";

const data = [
  { id: 1, title: "onan the Barbarian", year: "1982" },
  { id: 2, title: "Zonan the Barbarian", year: "2982" },
  { id: 3, title: "Donan the Barbarian", year: "5982" },
  { id: 4, title: "Conan the Barbarian", year: "15982" },
  { id: 5, title: "Bonan the Barbarian", year: "8982" },
  { id: 6, title: "Aonan the Barbarian", year: "9982" },
  { id: 7, title: "onan the Barbarian", year: "1982" },
  { id: 8, title: "Zonan the Barbarian", year: "2982" },
  { id: 9, title: "Donan the Barbarian", year: "5982" },
  { id: 10, title: "Conan the Barbarian", year: "15982" },
  { id: 11, title: "Bonan the Barbarian", year: "8982" },
  { id: 12, title: "Aonan the Barbarian", year: "9982" },
];

const customStyles = {
  rows: { style: { minHeight: "72px", } },
  headCells: { style: { paddingLeft: "8px", paddingRight: "8px", } },
  cells: { style: { paddingLeft: "8px", paddingRight: "8px", } },
};

function App() {
  // 初始化每列的搜索关键词状态
  const [searchTerms, setSearchTerms] = useState({
    title: "",
    year: ""
  });

  // 处理搜索输入变化
  const handleSearchChange = (column, value) => {
    setSearchTerms(prev => ({
      ...prev,
      [column]: value.toLowerCase()
    }));
  };

  // 利用useMemo缓存过滤后的数据,避免不必要的重渲染
  const filteredData = useMemo(() => {
    return data.filter(item => {
      // 检查每一列的搜索条件是否都满足
      return Object.entries(searchTerms).every(([key, term]) => {
        return item[key].toLowerCase().includes(term);
      });
    });
  }, [searchTerms]);

  // 自定义列配置,添加搜索框到表头
  const columns = [
    {
      name: "Name",
      selector: "title",
      sortable: true,
      middle: true,
      // 自定义表头组件
      header: () => (
        <div>
          <div>Name</div>
          <input
            type="text"
            placeholder="Search..."
            value={searchTerms.title}
            onChange={(e) => handleSearchChange("title", e.target.value)}
            style={{ width: "100%", marginTop: "4px", padding: "4px", fontSize: "0.9rem", boxSizing: "border-box" }}
          />
        </div>
      )
    },
    {
      name: "Year",
      selector: "year",
      sortable: true,
      middle: true,
      header: () => (
        <div>
          <div>Year</div>
          <input
            type="text"
            placeholder="Search..."
            value={searchTerms.year}
            onChange={(e) => handleSearchChange("year", e.target.value)}
            style={{ width: "100%", marginTop: "4px", padding: "4px", fontSize: "0.9rem", boxSizing: "border-box" }}
          />
        </div>
      )
    },
  ];

  return (
    <div className="App">
      <DataTable 
        title="Movies" 
        columns={columns} 
        data={filteredData} 
        striped
        highlightOnHover
        customStyles={customStyles}
        pagination
      />
    </div>
  );
}

export default App;

关键细节说明

  • 状态管理:用searchTerms对象存储每一列的搜索关键词,确保每个搜索框独立控制对应列的过滤条件
  • 性能优化:使用useMemo缓存过滤后的数据,只有当搜索关键词变化时才重新计算过滤结果,避免组件频繁重渲染
  • 表头自定义:通过columns数组中每个列的header属性,渲染包含标题和搜索框的自定义表头组件,样式可根据需求调整
  • 过滤逻辑:采用every方法确保只有满足所有列搜索条件的数据才会被保留,实现多列联合过滤

内容的提问来源于stack exchange,提问作者Komal Cr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:48:14