简单的分页组件(react)

101次阅读

共计 2060 个字符,预计需要花费 6 分钟才能阅读完成。

简单的分页组件 … 由于工作原因, 写过一段 vue, 现在入手 jquery. 自己是战五渣选手,为了巩固之前学过的 react,特意用 react 来实现,其实想用 jquery。github L6zt 代码效果如图:

思路:组件基本属性: cur 当前页码,all 总页码 space 页面显示数量 +1 才是 总数量组件整体状态
1、与首页相连, cur < space 基本满足 2、中间状态,cur > space && cur < all – space3、与末尾相连,cur > all – spacereact 基本操作子组件 Pagination 通过 props 更新状态, 和 state 无关。show code
// 判断 是不是数字
const isNumber = (num) => {
return typeof num === ‘number’;
}
class Pagination extends React.Component {
constructor (props) {
super(props);
}
// 点击回调事件
handleClick (item) {
// 父组件回调事件
this.props.cb(item);
}
render () {
let {cur, space, all} = this.props;
let pgObj = [];
// 给不同的元素 赋值 class
const checkClass = (role, active) => {
const defaultClass = ‘pg-span’;
if (active) {
return `${defaultClass} active`
}
switch (role) {
case 0: {
return `${defaultClass}`
}
case 1: {
return `${defaultClass}`
}
default: {

}
}
}
// 初始检查
if (all < space) {
all = space
}
if (cur <= 0) {
cur = 0
}
if (cur >= all) {
cur = all
}
// 阶段判断
if (cur < space) {
if (space === all) {
for (let i = 1; i <= space; i++) {
pgObj.push({
page: i,
role: 0,
key: i
})
}
} else {
for (let i = 1; i <= space; i ++) {
pgObj.push({
page: i,
role: 0,
key: i
})
}
pgObj.push({
page: ‘…’,
role: 1,
key: ‘next’
})
pgObj.push({
page: all,
role: 0,
key: all
})
}
} else if (cur >= space && cur <= all – space + 1) {
let odd = parseInt(space / 2);
pgObj.push({
page: 1,
role: 0,
key: 1
});
pgObj.push({
page: ‘…’,
role: 1,
key: ‘pre’
});
for (let i = cur – odd; i <= cur + odd ; i ++) {
pgObj.push({
page: i,
role: 1,
key: i
})
}
pgObj.push({
page: ‘…’,
role: 1,
key: ‘next’
});
pgObj.push({
page: all,
role: 1,
key: all
})
} else {
pgObj.push({
page: 1,
role: 0,
key: 1
});
pgObj.push({
page: ‘…’,
role: 1,
key: ‘pre’
});
for (let i = all – space + 1; i <= all; i ++) {
pgObj.push({
page: i,
role: 0,
key: i
})
};
}
return (
<section>
{
pgObj.map(item =>
(<span key={item.key}
className={checkClass(item.role, item.page === cur)}
onClick={() => {this.handleClick(item)}}
>
{item.page}
</span>))
}
</section>
)
}

}
class Root extends React.Component {
constructor (props) {
super(props);
this.state = {
cur: 1
};
this.handlePagination = this.handlePagination.bind(this);
}
handlePagination (item) {
const {page} = item;
if (isNumber(page)) {
this.setState({
cur: page
})
}
}
render() {
let {cur} = this.state;
console.log(cur);
return (
<div>
<Pagination cur={cur} all={100} space={8} cb={this.handlePagination} />
</div>
)
}
};
ReactDOM.render(
<Root></Root>,
document.getElementById(‘root’)
);

demo 地址

正文完
 0