【发布时间】:2019-11-17 22:13:02
【问题描述】:
我正在尝试使用reactstrap 作为 UI 库创建动态分页反应组件。我被困在完成相同的问题上。
UsersCard.js
import React, { Component } from 'react'
import axios from 'axios';
import PaginationTable from './PaginationTable';
export default class UsersCard extends Component {
constructor(props) {
super(props)
this.state = {
usersData: [],
loading: false,
per_page: 3,
current_page: 1,
total_data: '',
currentPosts: []
}
}
async componentDidMount(){
await axios.get('https://reqres.in/api/users')
.then(res => {
this.setState({
usersData: res.data.data,
loading: false,
total_data: res.data.data.length
})
})
.catch(err => console.log(err));
const indexOfLastPost = this.state.current_page * this.state.per_page;
const indexOfFirstPage = indexOfLastPost - this.state.per_page;
const currentPosts = this.state.usersData.slice(indexOfFirstPage, indexOfLastPost);
this.setState({ currentPosts })
}
handleClick = (number) => {
this.setState({
current_page: number
})
}
render() {
const { per_page, handleClick, total_data, current_page, currentPosts } = this.state;
return (
<div>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>email</th>
<th>Last Name</th>
</tr>
</thead>
{currentPosts.map(x => {
return(
<React.Fragment key={x.id}>
<tbody>
<tr>
<td>{x.id}</td>
<td>{x.first_name}</td>
<td>{x.email}</td>
<td>{x.last_name}</td>
</tr>
</tbody>
</React.Fragment>
)
})}
</table>
<PaginationTable
per_page={per_page}
current_page={current_page}
total_data={total_data}
handleClick={handleClick}
/>
</div>
)
}
}
PaginationTable.js
import React from 'react';
import { Pagination, PaginationItem, PaginationLink } from 'reactstrap';
const PaginationTable = ({ per_page, total_data, handleClick, current_page }) => {
let pageNumbers = [];
for(let i=1; i<= Math.ceil(total_data/per_page); i++)
{
pageNumbers.push(
<PaginationItem key={i} active={current_page === i ? true : false}>
<PaginationLink onClick={() => handleClick(i)} href="#">
{i}
</PaginationLink>
</PaginationItem>)
}
return(
<Pagination aria-label="Page navigation example">
<PaginationItem disabled={current_page <= 1}>
<PaginationLink onClick={()=>handleClick(current_page-1)}
previous
href="#"
/>
</PaginationItem>
{pageNumbers}
<PaginationItem disabled={current_page >= per_page - 1}>
<PaginationLink onClick={()=>handleClick(current_page + 1)}
next
href="#"
/>
</PaginationItem>
</Pagination>
)
}
导出默认分页表;
我的问题是这样的:
1) Reactstrap 分页 UI 未正确显示。
2) 每当我单击next 按钮时,它都会显示错误:TypeError: handleClick is not a function。
我对动态分页概念有点陌生,无法识别我遇到的错误。 Kindlt帮助解决同样的问题。也欢迎任何代码改进。
【问题讨论】:
-
你必须从父组件传递
this.handleClick -
它确实让我摆脱了点击错误,但它不起作用:/。你能帮忙吗?
-
@BoyWithSilverWings 你能帮我解决这个问题吗?这是演示链接:react-qxrpv8.stackblitz.io
标签: javascript reactjs pagination