React全家桶+共享单车实战开发-——7 AntD Table 基础表格

可参考:https://blog.csdn.net/qq_34235864/article/details/86580869

 一、基础表格

  • Table组件基础Api
  1. bordered属性:是否展示外边框和列边框
  2. columns属性:表格列的配置描述(即表头)
  3. dataSource属性:数据数组
  4. pagination属性:分页器,设为 false 时不展示和进行分页

  src->pages->table->basicTable.js

import React from 'react';
import {Card, Table} from 'antd';

export default class BasicTable extends React.Component{
    state={}
    componentDidMount(){
        const data = [
           {
                id:'0',
                userName:'Jack',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2000-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Tom',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Lily',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'08:00'
           },
        ]
        this.setState({
            dataSource:data
        })
    }
    render(){
        const columns = [
            {
                title:'id',
                dataIndex:'id'
            },{
                title:'用户名',
                dataIndex:'userName'
            },{
                title:'性别',
                dataIndex:'sex'
            },{
                title:'状态',
                dataIndex:'state'
            },{
                title:'爱好',
                dataIndex:'interest'
            },{
                title:'生日',
                dataIndex:'birthday'
            },{
                title:'地址',
                dataIndex:'address'
            },{
                title:'早起时间',
                dataIndex:'time'
            }
        ]
        return (
            <div>
                <Card title="基础表格">
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource}
                        pagination={false}
                    />
                </Card>
            </div>
        );
    }
}



二、项目工程化----Table 动态渲染

  • 项目工程化---Mock数据
  • 项目工程化---Axios封装
  • 项目工程化---Loading 处理、错误拦截(动态添加key值)

Easy Mock用法及Mock.js规范 

1、获取mock数据

src->pages->table->basicTable.js

import React from 'react';
import {Card, Table} from 'antd';
import axios from 'axios'
export default class BasicTable extends React.Component{
    state={
        dataSource2:[]
    }
    componentDidMount(){
        const data = [
           {
                id:'0',
                userName:'Jack',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2000-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Tom',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Lily',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'08:00'
           },
        ]
        this.setState({
            dataSource:data
        })
        this.request();
    }

    //动态获取mock数据
    request = ()=>{
        let baseUrl = 'https://www.easy-mock.com/mock/5d6499edd61d1455304561c4/mockapi'
        axios.get(baseUrl+'/table/list').then((res)=>{
            if(res.status=='200' && res.data.code== 0){
                this.setState({
                        dataSource2:res.data.result
                })
            }
        })
    }



    render(){
        const columns = [
            {
                title:'id',
                dataIndex:'id'
            },{
                title:'用户名',
                dataIndex:'userName'
            },{
                title:'性别',
                dataIndex:'sex'
            },{
                title:'状态',
                dataIndex:'state'
            },{
                title:'爱好',
                dataIndex:'interest'
            },{
                title:'生日',
                dataIndex:'birthday'
            },{
                title:'地址',
                dataIndex:'address'
            },{
                title:'早起时间',
                dataIndex:'time'
            }
        ]
        return (
            <div>
                <Card title="基础表格">
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource}
                        pagination={false}
                    />
                </Card>
                <Card title="动态数据渲染" style={{margin:'10px 0'}}>
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource2}
                        pagination={false}
                    />
                </Card>
            </div>
        );
    }
}



2、封装Axios   获取mock数据

src->axios->index.js:定义ajax方法,封装axios异步获取Easy Mock项目虚拟数据的过程【项目工程化】

import JsonP from 'jsonp'
import axios from 'axios'
import {Modal} from 'antd'

export default class Axios{
     static jsonp(options){
         return new Promise((resolve, reject) => {
             JsonP(options.url,{
                 param:'callback'
             }, function (err, response) {
                if(response.status === 'success'){
                    resolve(response);
                }else{
                    reject(response.message);
                }
             })
         })
     }

     static ajax(options){
         let baseApi = 'https://www.easy-mock.com/mock/5d6499edd61d1455304561c4/mockapi'
         return new Promise((resolve,reject)=>{
             axios({
                 url: options.url,
                 method:'get',
                 baseURL:baseApi,
                 timeout:5000,
                 params: (options.data && options.data.params) || ''
             }).then((response)=>{
                 if(response.status == '200'){
                    let res = response.data;
                    if(res.code =='0'){
                        resolve(res);
                    }else{
                        Modal.info({
                            title:"提示",
                            content:res.msg
                        })
                    }
                 }else{
                     reject(response.data);
                 }
             })
         })
     }
}  

src->pages->table->basicTable.js    

定义request方法,调用axios动态获取Mock数据

import React from 'react';
import {Card, Table} from 'antd';
import axios from './../../axios/index'

export default class BasicTable extends React.Component{
    state={
        dataSource2:[]
    }
    componentDidMount(){
        const data = [
           {
                id:'0',
                userName:'Jack',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2000-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Tom',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Lily',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'08:00'
           },
        ]
        this.setState({
            dataSource:data
        })
        this.request();
    }

    //动态获取mock数据
    request = ()=>{
        axios.ajax({
            url:'/table/list',
            data:{
                params:{
                    page:1
                }
            }
        }).then((res)=>{
            if(res.code == '0'){
                this.setState({
                    dataSource2:res.result
                })
            }
        })
    }



    render(){
        const columns = [
            {
                title:'id',
                dataIndex:'id'
            },{
                title:'用户名',
                dataIndex:'userName'
            },{
                title:'性别',
                dataIndex:'sex'
            },{
                title:'状态',
                dataIndex:'state'
            },{
                title:'爱好',
                dataIndex:'interest'
            },{
                title:'生日',
                dataIndex:'birthday'
            },{
                title:'地址',
                dataIndex:'address'
            },{
                title:'早起时间',
                dataIndex:'time'
            }
        ]
        return (
            <div>
                <Card title="基础表格">
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource}
                        pagination={false}
                    />
                </Card>
                <Card title="动态数据渲染" style={{margin:'10px 0'}}>
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource2}
                        pagination={false}
                    />
                </Card>
            </div>
        );
    }
}



3、Loading 处理、错误拦截

  • public-->index.html   root后面增加如下代码
    <div id="root"></div>
    <div class="ajax-loading" id="ajaxLoading" style="display: none;">
        <div class="overlay"></div>
        <div class="loading">
            <img src="https://media.number-7.cn/ebike-h5/static/images/common/loading.gif" alt="">
            <span>加载中,请稍后...</span>
        </div>
     </div>
  • style-->loading.less
/** load **/
.ajax-loading{
    display: none;
    .loading{
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      padding:0 40px;
      height: 80px;
      line-height: 80px;
      background: rgba(0, 0, 0, 0.75);
      border-radius: 6px;
      text-align: center;
      z-index: 9999;
      font-size:@fontD;
      color:#fff;
      img{
        width: 32px;
        vertical-align: middle;
      }
      span{
        margin-left:12px;
      }
    }
    .overlay{
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 9998;
      background: rgb(255, 255, 255);
      opacity: 0.1;
    }
  }
  
  /****/

style-->common.less引入loading.less

@import './loading.less';

axios-->index.js   修改如下:

     static ajax(options){
         let loading;
         if(options.data && options.data.isShowLoading !== false){
             loading = document.getElementById('ajaxLoading')
             loading.style.display = 'block';
         }
         let baseApi = 'https://www.easy-mock.com/mock/5d6499edd61d1455304561c4/mockapi'
         return new Promise((resolve,reject)=>{
             axios({
                 url: options.url,
                 method:'get',
                 baseURL:baseApi,
                 timeout:5000,
                 params: (options.data && options.data.params) || ''
             }).then((response)=>{
                if(options.data && options.data.isShowLoading !== false){
                    loading = document.getElementById('ajaxLoading')
                    loading.style.display = 'none';
                }
                 if(response.status == '200'){
                    let res = response.data;
                    if(res.code =='0'){
                        resolve(res);
                    }else{
                        Modal.info({
                            title:"提示",
                            content:res.msg
                        })
                    }
                 }else{
                     reject(response.data);
                 }
             })
         })
     }
  • src-->pages-->table-->basicTable.js  中
    //动态获取mock数据
    request = ()=>{
        axios.ajax({
            url:'/table/list',
            data:{
                params:{
                    page:1
                },
                isShowLoading:false
            }
        }).then((res)=>{
            if(res.code == '0'){
                this.setState({
                    dataSource2:res.result
                })
            }
        })
    }

此时不显示Loading加载

isShowLoading默认为true时:

4、表格字段映射,如将性别、状态、爱好的值转为汉字

        const columns = [
            {
                title:'id',
                dataIndex:'id'
            },{
                title:'用户名',
                dataIndex:'userName'
            },{
                title:'性别',
                dataIndex:'sex',
                render(sex){
                    return sex ==1 ?'男':'女'
                }
            },{
                title:'状态',
                dataIndex:'state',
                render(state){
                    let config = {
                        '1':'咸鱼一条',
                        '2':'风华浪子',
                        '3':'北大才子',
                        '4':'百度FE',
                        '5':'创业者'
                    }
                    return config[state];
                }
            },{
                title:'爱好',
                dataIndex:'interest',
                render(interest){
                    let config = {
                        '1':'游泳',
                        '2':'打篮球',
                        '3':'踢足球',
                        '4':'跑步',
                        '5':'爬山',
                        '6':'骑行',
                        '7':'桌球',
                        '8':'麦霸'
                    }
                    return config[interest];
                }
            },{
                title:'生日',
                dataIndex:'birthday'
            },{
                title:'地址',
                dataIndex:'address'
            },{
                title:'早起时间',
                dataIndex:'time'
            }
        ]

 

三、表格单选

  • rowSelection属性:列表项是否可选择,对象
  • 配置项:
  1. type:单选/多选
  2. selectedRowKeys:指定选中项的key数组,需要和onChange进行配合(单选,仅onRow事件即可)
const selectedRowKeys = this.state.selectedRowKeys;
const rowSelection = {
      type: 'radio',
      selectedRowKeys
}
  • onRow事件:控制点击某一行,设置行属性
 <Card title="Mock-单选" style={{margin: '10px 0'}}>
      <Table 
            bordered
            rowSelection={rowSelection}
            onRow={(record, index) => {
                  return {
                       onClick: () => { 
                            this.onRowClick(record, index)
                       }  //点击行
                  }
            }}
            columns={columns}
            dataSource={this.state.dataSource2}
            pagination={false}
      />
</Card>
  • 提取出onRowClick方法:获取当前点击行的数据项record和索引index
//点击某一行 record:当前点击行的数据项 index:当前点击行的索引
onRowClick = (record, index) => {
        let selectKey = [index];
        Modal.info({
            title: '信息',
            content: `用户名:${record.userName},用户爱好:${record.interest}`
        });
        this.setState({
            selectedRowKeys: selectKey,
            selectedItem: record
        })
}

此时basicTable.js全部代码如下:

import React from 'react';
import {Card, Table, Modal} from 'antd';
import axios from './../../axios/index'

export default class BasicTable extends React.Component{
    state={
        dataSource2:[]
    }
    componentDidMount(){
        const data = [
           {
                id:'0',
                userName:'Jack',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2000-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Tom',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'09:00'
           },{
                id:'1',
                userName:'Lily',
                sex:'1',
                state:'1',
                interest:'1',
                birthday:'2010-01-01',
                address:'北京市海淀区奥林匹克公园',
                time:'08:00'
           },
        ]
        data.map((item,index)=>{
            item.key = index;
        })
        this.setState({
            dataSource:data
        })
        this.request();
    }

    //动态获取mock数据
    request = ()=>{
        axios.ajax({
            url:'/table/list',
            data:{
                params:{
                    page:1
                },
                isShowLoading:true
            }
        }).then((res)=>{
            if(res.code == '0'){
                res.result.map((item,index)=>{
                    item.key = index;
                })
                this.setState({
                    dataSource2:res.result
                })
            }
        })
    }

    onRowClick = (record, index)=>{
        let selectKey = [index];
        Modal.info({
            title:'信息',
            content:`用户名:${record.userName}, 用户爱好:${record.interest}`
        })
        this.setState({ 
            selectedRowKeys:selectKey,
            selectedItem:record
        })
    }

    render(){
        const columns = [
            {
                title:'id',
                dataIndex:'id'
            },{
                title:'用户名',
                dataIndex:'userName'
            },{
                title:'性别',
                dataIndex:'sex',
                render(sex){
                    return sex ==1 ?'男':'女'
                }
            },{
                title:'状态',
                dataIndex:'state',
                render(state){
                    let config = {
                        '1':'咸鱼一条',
                        '2':'风华浪子',
                        '3':'北大才子',
                        '4':'百度FE',
                        '5':'创业者'
                    }
                    return config[state];
                }
            },{
                title:'爱好',
                dataIndex:'interest',
                render(interest){
                    let config = {
                        '1':'游泳',
                        '2':'打篮球',
                        '3':'踢足球',
                        '4':'跑步',
                        '5':'爬山',
                        '6':'骑行',
                        '7':'桌球',
                        '8':'麦霸'
                    }
                    return config[interest];
                }
            },{
                title:'生日',
                dataIndex:'birthday'
            },{
                title:'地址',
                dataIndex:'address'
            },{
                title:'早起时间',
                dataIndex:'time'
            }
        ]

        // const { selectedRowKeys } = this.state;
        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            type:'radio',
            selectedRowKeys
        }
        return (
            <div>
                <Card title="基础表格">
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource}
                        pagination={false}
                    />
                </Card>
                <Card title="动态数据渲染-Mock" style={{margin:'10px 0'}}>
                    <Table
                        bordered
                        columns={columns}
                        dataSource={this.state.dataSource2}
                        pagination={false}
                    />
                </Card>
                <Card title="Mock-单选" style={{margin:'10px 0'}}>
                    <Table
                        bordered
                        rowSelection={rowSelection}
                        onRow={(record,index)=>{
                            return {
                                onClick:()=>{
                                    this.onRowClick(record,index);
                                },//点击行
                            }
                        }}
                        columns={columns}
                        dataSource={this.state.dataSource2}
                        pagination={false}
                    />
                </Card>
            </div>
        );
    }
}



四、表格复选

  • 配置rowSelection属性对象
  1. 添加onChange事件
  2. selectedRowKeys:当前选中的行索引
  3. selectedRows:当前选中的行对象
const rowCheckSelection = {
            type: 'checkbox',
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                // let ids = []
                // selectedRows.map((item) => {
                //    ids.push(item.id)
                // })
                this.setState({
                    selectedRowKeys, //必需
                    // selectedIds: ids,
                    selectedRows
                })
            }
}

 

  • 选中多行执行操作

  1. 获取state中的seletedRows对象,遍历得到item对象

  2. 利用item.id执行操作
  3. 执行完操作,需要重新刷新页面:调用this.request()

    // 多选执行删除操作
    handleDelete = (()=>{
        let rows = this.state.selectedRows;
        let ids = [];
        rows.map((item) => {
            ids.push(item.id)
        })
        Modal.confirm({
            title:'删除提示',
            content:`您确定要删除这些数据吗?${ids.join(',')}`,
            onOk:()=>{
                message.success('删除成功');
                this.request(); //重新刷新页面
            }
        })
    })

4、request方法中:当获取数据成功后,重置state中当前选中项参数均为空

selectedRowKeys: [], //重置
selectedRows: null,

5、其它,同单选

<Card title="Mock-复选" style={{margin: '10px 0'}}>
        <div style={{marginBottom: 10}}>
               <Button onClick={this.handleDelete}>删除</Button>
        </div>
        <Table 
                bordered
                rowSelection={rowCheckSelection}
                onRow={(record, index) => {
                        return {
                            onClick: () => { 
                                this.onRowClick(record, index)
                            }  //点击行
                        }
                }}
                columns={columns}
                dataSource={this.state.dataSource2}
                pagination={false}
        />
</Card>

五、表格分页

  •  src->utils->utils.js:封装pagination分页工具函数 【项目工程化】
pagination(data,callback){
   return {
        onChange: (current) => {
            callback(current)   //回调函数返回当前页
        },
        current: data.page,
        pageSize: data.page_size,
        total: data.total,
        showTotal: () => {
            return  `共${data.total}条`
        },
        showQuickJumper: true  //是否快速跳转至某一页
   }
}  

注意:获取data对象的数据,需要符合Easy Mock中模拟数据的数据结构!!!

Mock数据修改如下:

  • request方法中:当获取数据成功后,调用Utils.pagination()给state添加并配置pagination
import Utils from './../../utils/utils'
 
let _this = this; //保留外层this,否则this指向会有问题
 
pagination: Utils.pagination(res,(current) => {
       _this.params.page = current;
       this.request();
})
  • Table组件中使用pagination属性
<Card title="Mock-表格分页" style={{margin: '10px 0'}}>
      <Table 
                bordered
                columns={columns}
                dataSource={this.state.dataSource2}
                pagination={this.state.pagination}
       />
</Card>

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值