首页 > 解决方案 > 在 React with Pagination 中显示图像列表

问题描述

我对 React 很陌生,所以请在这里帮助我。我有一个简单的 React 函数组件,它有一个图像标签,我想在我的主组件中使用这个图像组件并渲染它。这很好用。

我想用分页渲染相同的图像组件 10-50 次。有人可以给我发送链接或帮助我如何显示包含分页的功能组件的图像列表。

图像组件

function ImageFunctionComponent(){
    return (
   <img alt='Test' 
   src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcStvpLEylZEJ-dJLEYU3ApbyDooj-_98dYQuw&usqp=CAU"/>   
        );
}

export default ImageFunctionComponent;

index.js

class ImageTest extends React.Component {
  render(){
    return(
   <>
  <ImageFunctionComponent></ImageFunctionComponent>
  <ImageFunctionComponent></ImageFunctionComponent>
  <ImageFunctionComponent></ImageFunctionComponent>
  <ImageFunctionComponent></ImageFunctionComponent>
  <ImageFunctionComponent></ImageFunctionComponent>
  <ImageFunctionComponent></ImageFunctionComponent>
  
</>
)
;
  }
}

const element=<ImageTest />

ReactDOM.render(element,document.getElementById("root"));

我只想在一页上显示两个图像,然后有一个分页来显示接下来的两个图像。我如何在 React 中做到这一点?

标签: javascriptreactjspagination

解决方案


首先针对这个具体案例。我会将图像存储在分页组件内的数组中,并像这样存储页面计数器

const LIMIT = 2;
const [images, setImages] = useState([<ImageFunctionComponent/>, <ImageFunctionComponent/>, ...]);

const [page, setPageCounter] = useState(0);

然后将分页的左箭头绑定到:setPageCounter(page - 1); // taking in count if page is not zero 和右箭头绑定到setPageCounter(page + 1); // taking in count page * LIMIT < array.length

然后在渲染中只是返回:

const renderImages = [];
for(let i = page*LIMIT; i < page*LIMIT + LIMIT; i++) {
        renderImages.push(images[i]);
}
return (<>
        renderImages
</>);

推荐阅读