javascript - 在 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 中做到这一点?
解决方案
首先针对这个具体案例。我会将图像存储在分页组件内的数组中,并像这样存储页面计数器
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
</>);
推荐阅读
- node.js - NestJS 防止在开发中重新加载服务器
- javascript - JS 或 Jquery:如何将“选项”添加到复选框
- java - 使用 JDBCTemplate 时,SQL `IN` 在 Spring Boot 中不起作用
- css - 如何将 flexbox 项目连续居中?
- java - 爪哇 | 系统日志服务器 | 如何使用 Java 代码设置可公开访问的 Syslog 服务器
- windows - windows上的GSL找不到头文件
- java - 在命令提示符处覆盖 Spring Boot Profiles 中的属性
- python-3.x - 有条件地将数据附加到 pandas 数据帧
- python - Tweepy - 获取原始推文的所有转推 ID
- c# - 哪个选项在大规模上更好 - 每个用户的循环任务或循环并为所有用户完成工作的单个任务?