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

如何使用React创建筛选器?React新手开发技术求助

给React分页组件添加筛选器的实现方案

嘿,作为React初学者能想到给分页组件加筛选功能,这思路很赞!我来帮你把这个功能实现出来,咱们一步步来~

首先先看你现有的代码:

class Pagination extends React.Component { 
  constructor() { 
    super(); 
    this.state = { 
      elementsPerPage:3, 
      currentPage:0, 
      peoples:[ 
        {id:0, name:"jee"}, 
        {id:1, name:"jiii"}, 
        {id:2, name:"jaa"}, 
        {id:3, name:"joo"}, 
        {id:4, name:"daaa"}, 
        {id:5, name:"hehee"}, 
        {id:6, name:"hoho"}, 
        {id:7, name:"ihihi"}, 
        {id:8, name:"huheue"}, 
        {id:9, name:"haha"}, 
        {id:10, name:"brbr..."}
      ]
    }; 
  }
}

要实现筛选器,咱们需要做这几件事:

  • 新增状态存储用户的搜索关键词
  • 添加搜索输入框并绑定输入事件
  • 编写过滤逻辑,根据关键词筛选人员列表
  • 让分页逻辑基于过滤后的列表来计算

下面是修改后的完整代码,每部分都加了注释说明:

class Pagination extends React.Component { 
  constructor() { 
    super(); 
    this.state = { 
      elementsPerPage: 3, 
      currentPage: 0, 
      searchTerm: '', // 新增:存储用户输入的搜索关键词
      peoples: [ 
        {id:0, name:"jee"}, 
        {id:1, name:"jiii"}, 
        {id:2, name:"jaa"}, 
        {id:3, name:"joo"}, 
        {id:4, name:"daaa"}, 
        {id:5, name:"hehee"}, 
        {id:6, name:"hoho"}, 
        {id:7, name:"ihihi"}, 
        {id:8, name:"huheue"}, 
        {id:9, name:"haha"}, 
        {id:10, name:"brbr..."}
      ]
    }; 
    // 绑定this,避免类方法里this指向问题
    this.handleSearchChange = this.handleSearchChange.bind(this);
    this.handlePageChange = this.handlePageChange.bind(this);
  }

  // 处理搜索输入变化的函数
  handleSearchChange(e) {
    this.setState({
      searchTerm: e.target.value,
      currentPage: 0 // 搜索时自动回到第一页,避免出现空页面
    });
  }

  // 处理分页切换的函数
  handlePageChange(pageNumber) {
    this.setState({ currentPage: pageNumber });
  }

  render() {
    // 第一步:根据搜索关键词过滤人员列表,忽略大小写提升体验
    const filteredPeoples = this.state.peoples.filter(person => 
      person.name.toLowerCase().includes(this.state.searchTerm.toLowerCase())
    );

    // 第二步:基于过滤后的列表计算当前页要显示的内容
    const indexOfLastElement = (this.state.currentPage + 1) * this.state.elementsPerPage;
    const indexOfFirstElement = indexOfLastElement - this.state.elementsPerPage;
    const currentElements = filteredPeoples.slice(indexOfFirstElement, indexOfLastElement);

    // 第三步:计算总页数,用于渲染分页按钮
    const totalPages = Math.ceil(filteredPeoples.length / this.state.elementsPerPage);
    const pageNumbers = [];
    for (let i = 0; i < totalPages; i++) {
      pageNumbers.push(i);
    }

    return (
      <div>
        {/* 添加搜索输入框 */}
        <input
          type="text"
          placeholder="搜索姓名..."
          value={this.state.searchTerm}
          onChange={this.handleSearchChange}
          style={{ marginBottom: '1rem', padding: '0.5rem' }}
        />

        {/* 渲染当前页的人员列表 */}
        <ul>
          {currentElements.map(person => (
            <li key={person.id}>{person.name}</li>
          ))}
        </ul>

        {/* 渲染分页按钮 */}
        <div>
          {pageNumbers.map(number => (
            <button
              key={number}
              onClick={() => this.handlePageChange(number)}
              style={{ 
                margin: '0 0.2rem', 
                padding: '0.3rem 0.8rem',
                backgroundColor: this.state.currentPage === number ? '#007bff' : '#fff',
                color: this.state.currentPage === number ? '#fff' : '#000',
                border: '1px solid #007bff',
                borderRadius: '4px',
                cursor: 'pointer'
              }}
            >
              {number + 1}
            </button>
          ))}
        </div>
      </div>
    );
  }
}

// 渲染组件
ReactDOM.render(<Pagination />, document.getElementById('root'));

几个关键细节说明:

  • 大小写不敏感的搜索:把姓名和搜索关键词都转成小写,这样用户输入"JEE"或者"jee"都能找到对应的人员,体验更友好
  • 搜索时重置分页:每次输入搜索词时自动回到第一页,防止用户在第3页搜索后,过滤后的列表不足3条导致显示空内容
  • 分页逻辑绑定过滤后的数据:所有分页计算都基于filteredPeoples,确保显示的内容是筛选后的结果

这样你就能拥有一个带筛选功能的分页组件啦,试试输入不同的关键词,看看分页和筛选是不是正常工作~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:41:27