要在不同的页面上使用同一个分页和模糊查询语句,你可以将这些语句封装成一个函数或者组件,然后在需要的页面上引用。以下是一个示例:

  1. 创建一个名为paginationAndSearch的函数,该函数接收参数pagepageSizesearchKeyword,并返回一个分页和模糊查询的结果:
function paginationAndSearch(page, pageSize, searchKeyword) {
  // 分页逻辑
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;

  // 模糊查询逻辑
  const filteredData = data.filter(item =>
    item.name.toLowerCase().includes(searchKeyword.toLowerCase())
  );

  // 返回结果
  return {
    totalItems: filteredData.length,
    totalPages: Math.ceil(filteredData.length / pageSize),
    currentPageData: filteredData.slice(startIndex, endIndex),
  };
}
  1. 在需要使用分页和模糊查询的页面上,调用paginationAndSearch函数并传入相应的参数,获取结果并展示:
import React, { useState } from 'react';

function MyPage() {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchKeyword, setSearchKeyword] = useState('');
  const { totalItems, totalPages, currentPageData } = paginationAndSearch(
    page,
    pageSize,
    searchKeyword
  );

  // 更新页码
  const handlePageChange = (newPage) => {
    setPage(newPage);
  };

  // 更新每页显示数量
  const handlePageSizeChange = (newPageSize) => {
    setPageSize(newPageSize);
    setPage(1); // 切换每页显示数量后重置页码为第一页
  };

  // 更新搜索关键字
  const handleSearch = (keyword) => {
    setSearchKeyword(keyword);
    setPage(1); // 更新搜索关键字后重置页码为第一页
  };

  return (
    <div>
      {/* 搜索框 */}
      <input type="text" onChange={(e) => handleSearch(e.target.value)} />

      {/* 数据展示 */}
      {currentPageData.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}

      {/* 分页 */}
      <Pagination
        current={page}
        pageSize={pageSize}
        total={totalItems}
        onChange={handlePageChange}
      />

      {/* 每页显示数量选择 */}
      <PageSizeSelector value={pageSize} onChange={handlePageSizeChange} />
    </div>
  );
}

通过将分页和模糊查询的逻辑封装成一个函数,可以在不同的页面上复用该逻辑,提高代码的可维护性和重用性。根据具体的技术栈和需求,你可能需要对上述示例代码进行适当的修改。

不同的页面使用同一个分页和模糊查询语句

原文地址: https://www.cveoy.top/t/topic/i92R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录