首页 > 解决方案 > 如何在node.js中的某些数字后显示分页点并做出反应

问题描述

我想显示压缩的分页数字1,2,3 ... 56, 57,请查看我目前情况的附件截图以及我的期望

在此处输入图像描述

下面是我为图片展示完成的 API 代码和前端代码。

// Backend

const totalPages = Math.ceil(totalPages / limit);
res.send({
  posts,
  totalPages,
});

// Output

totalPages = 107;
posts = 2140;

// Frontend

const pager = () => {
  const paginate = [];
  for (let i = 1; i <= totalPages; i++) {
    // console.log('000')
    paginate.push(
      <Link href={`?page=${i}`} key={i}>
        <a>{i}</a>
      </Link>
    );
  }
  return paginate;
};

我想我可以解释我想要什么,但如果您有任何困惑,请在评论中告诉我。

提前致谢。

根据答案更新

在此处输入图像描述

请看这个截图,之后3应该会来4, 5等等...

基于@Andy

标签: javascriptnode.jsreactjspagination

解决方案


只需相应地设置您的条件。为了获得更好的导航体验,您可能还应该考虑当前页面,并至少将之前和之后的页面添加到导航中。像1 2 3 ... 56 57 58 ... 100 101 102

const pager = () => {
  let pagination = [], i = 1;
  
  while (i <= totalPages) {
    if (i <= 3 || //the first three pages
        i >= totalPages - 2 || //the last three pages
        i >= currentPage - 1 && i <= currentPage + 1) { //the currentPage, the page before and after
      pagination.push(
        <Link href={`?page=${i}`} key={i}> 
          <a>{i}</a> 
        </Link>
      );
      i++;
    } else { //any other page should be represented by ...
      pagination.push(<div>...</div>);
      //jump to the next page to be linked in the navigation
      i = i < currentPage ? currentPage - 1 : totalPages - 2;
    }
  }
  return pagination;
}

推荐阅读