Quiero mostrar los números de paginación comprimidos como 1,2,3 ... 56, 57 , vea esta captura de pantalla adjunta de mi situación actual y lo que espero
a continuación se encuentran mis códigos API y códigos de interfaz que se han realizado para mostrar imágenes.
// 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; };Creo que puedo explicar lo que quiero, pero si tiene alguna confusión, hágamelo saber en el comentario.
Gracias por adelantado.
Actualización basada en la respuesta
Por favor, mira esta captura de pantalla, después 3 debería venir 4, 5 ... y así sucesivamente.
Basado en @Andy
Creo que será más fácil si intenta con el paquete NPM porque ha hecho el backend por completo y para el frontend, puede probar con este como el siguiente enlace
Y la demostración está aquí.
Ejemplo de código como el siguiente
import React, { Component } from 'react' import Pagination from 'next-pagination' class Example extends Component { render() { return <Pagination total={1000} /> } }y la salida es
Por cierto, puede visitar el enlace del administrador de paquetes para obtener todos los detalles.
Creo que puede ayudar.
Simplemente establezca sus condiciones en consecuencia. Y para una mejor experiencia de navegación, probablemente también debería considerar la página actual y agregar al menos la página anterior y posterior a su navegación. Me gusta 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; }En lugar de iterar a través de la totalidad de n de totalPages , hágalo por etapas. Primero obtenga los enlaces de la primera página usando un for...loop , luego aplique los puntos, luego use un bucle similar para obtener los enlaces de la última página.
Este ejemplo usa un componente Paginator para encapsular el código que luego puede importar al componente que lo requiere.
function Paginator({ totalPages }) { const pagination = []; function createLink(i) { const page = `?page=${i}`; return ( <div className="page"> <a href={page} key={i}>{i}</a> </div> ); } function createDots() { return <div className="page">...</div>; } // If there are no pages return a message if (!totalPages) return <div>No pages</div>; // If totalPages is less than seven, iterate // over that number and return the page links if (totalPages < 7) { for (let i = 1; i <= totalPages; i++) { pagination.push(createLink(i)); } return pagination; } // Otherwise create the first three page links for (let i = 1; i <= 3; i++) { pagination.push(createLink(i)); } // Create the dots pagination.push(createDots()); // Last three page links for (let i = totalPages - 2; i <= totalPages; i++) { pagination.push(createLink(i)); } return pagination; } function Example() { // Sample array of possible totalPages // Run the snippet again to see the change in output const arr = [0, 10, 107, 50, 100, 200, 1000, 45, 9, 3]; // Pick a total const totalPages = arr[Math.floor(Math.random() * arr.length)]; return <Paginator totalPages={totalPages} />; }; // Render it ReactDOM.render( <Example />, document.getElementById("react") ); .page { display: inline-block; padding: 0.5em; margin-left: 0.2em; border: 1px solid #666666; } .page a { color: black; text-decoration: none; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="react"></div>