react中基于ant-Design二次封装分页组件

一、组件中使用

import Pagination from '@components/pagination';

this.state = {
	total: 50, //总页数
    current:1,
    pageSize:10,    
}
//初始化时自调用一次,用于请求借口数据
componentDidMount() {
  this.onChangeCurPageOrPageSize(1, 10)
}

	// render分页
	<Pagination
	  current = { this.state.current }
	  pageSize = { this.state.pageSize }
	  total={this.state.total}
	  handleChange={this.onChangeCurPageOrPageSize} //当前页及条数改变都会从子组件触发此方法,用于传递页码和条数
	  pageSizeOptions={['10','20','30']} // 针对不同的组件需求传递每次多少条,不传已在分页组件写默认值了
	></Pagination>

// 查询按钮
searchBtn = (e) => {
  // 如果是表单的提交,阻止默认行为,避免你的路径上多了个?
  e && e.preventDefault()
  this.onChangeCurPageOrPageSize(1, this.state.pageSize)
}
// 重置
handleReset = () => {
  this.props.form.resetFields();
  this.onChangeCurPageOrPageSize(1, 10);
}
 //分页事件
onChangeCurPageOrPageSize = (current, pageSize) => { //参数为当前页,每页多少条
  this.setState(() => ({ current, pageSize }), () => { this.handleSearch() })
}

//借口请求数据
handleSearch = (e) => {
	...
}

二、pagination.js

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { Pagination } from 'antd';
class reportTemplateItem extends Component {
  static propTypes = {
    pageSizeOptions: PropTypes.array,
    total: PropTypes.number,
    current: PropTypes.number,
    pageSize: PropTypes.number
  }
  static defaultProps = {
    pageSizeOptions: ['5', '10', '20'],
    total: 0,  //必传,不解释
    current: 1, //必传 ,用于查询新条件,重置,条数改变跳转到第一页(用于分页组件改变)
    pageSize: 5 //必传 ,用于查询新条件,重置,初始化每页条数(用于分页组件改变)
  }
  constructor(props) {
    super(props);
  }
  render() {
    const { pageSizeOptions, total, current, pageSize } = this.props;
    return ( 
      <Fragment>
        {total?
          <div className="pagination" style={{marginTop:20,float:"right"}}>
            <Pagination 
            pageSizeOptions = { pageSizeOptions }
            pageSize = { pageSize }
            showQuickJumper 
            showSizeChanger 
            showTotal = { this.showTotal }
            current = {current }
            total = { total }
            onChange = { this.onChange }
            onShowSizeChange = { this.onShowSizeChange }
            style={{float:"right"}} />
          </div>:''
        }
      </Fragment>
    )
  }
  showTotal(total) {
    return `总计 ${total} 条`;
  }
  // 页码变化时将当前页和每页条数传出去
  onChange = (pageNumber, pageSize) => {
    // console.log('onChange: ', pageNumber, pageSize);
    this.props.handleChange(pageNumber, pageSize)
  }
  // 每页条数变化时将当前页和每页条数传出去
  onShowSizeChange=(current, pageSize)=> {
    // console.log("onShowSizeChange:",current, pageSize);
    this.props.handleChange(1, pageSize)
  }
}
export default reportTemplateItem;

你可能感兴趣的:(react.js)