(记录笔记6)——6.1 Table基础表格

6.1 Table基础表格

展示行列数据

一.基础表格

1.Table组件

  • 引入Table:import {Table} from “antd”;

  • 通过指定 columns + dataSource实现一个基础表格

  • columns={columns}
    dataSource={this.state.dataSource}

  • 通过指定pagination + bordered控制边框显示 和 分页

  •  //bordered    配置边框
     //不显示分页     去掉分页
     // +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:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      },
      {
        id:'2',
        userName: 'Lily',
        sex:'1',
        state:'1',
        interest:'1',
        birthday:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      }
    ]
    //将数据存入state中保存
    this.setState({
      dataSource:data
    });
  }

  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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'
      }
    ]
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    return (
      <div>
        <Card title="基础表格">
          <Table
            bordered
            columns={columns}
            dataSource={this.state.dataSource}
            pagination={false}
          >

          </Table>
        </Card>
      </div>
    );
  }
}


二.Table动态渲染

项目工程化:

  • Mock数据(第三方工具)-----------https://easy-mock.com/login

    • 可以查看Mockjs规范
    • Mock.js语法
  • Axios-----------封装

    • + import axios from 'axios';
      

      npm官网查询插件的使用

    • componentDidMount() {
          ...
      	this.request();//初始化调用数据
      }
      
      // 动态获取mock数据  then  成功时打印数据
      request=()=>{
          const baseUrl = 'https://easy-mock.com/mock/5c0893b83b84ee1919884836/mock.api';
          axios.get(baseUrl+'/table/list1').then((res)=>{
              console.log(JSON.stringify(res));
          })
      }
      render() 
      
  • Loading处理 ,错误拦截

  • mock数据:

{
   "code": 0,
   "msg": "",
   "result|10": [{
   	"id|+1": 1,
   	userName: '@cname',
   	"sex|1-2": 1,
   	"state|1-5": 1,
   	"interest|1-8": 1,
   	isMarried: "1",
   	birthday: '2000-01-01',
   	address: '北京市海淀区奥林匹克公园',
   	time: '09:00'
   	}],
   }

三 封装axios Api

//src/axios/index.js
//对jsonp的方法进行封装
import JsonP from "jsonp";//*导入jsonp的插件
import axios from 'axios';//*导入axios插件
import {Modal} from "antd";
//导出一个对象供其他对象进行使用
export default class Axios {
  static jsonp(options) {//定义静态的方法   jsonp  供其他页面进行使用
    return new Promise((resolve, reject) => {//使用Promise解决函数间的嵌套问题   链式调用
      JsonP(options.url, {
        param: 'callback'
      }, function (err, response) {
        //to-do
        //传入JsoP的对象进行操作
        //如果返回的对象是成功,使用resolve方法进行返回
        //debugger;//通过这个打断点
        if (response.status == 'success') {//成功后  用resolve返回数据
          resolve(response);
        } else {    //失败后用reject返回数据
          reject(response.message);
        }
      })
    })
  }

  static ajax(options) {//封装axios   定义为ajax请求,使用Promise
    const baseApi = 'https://easy-mock.com/mock/5c0893b83b84ee1919884836/mock.api';
    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
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:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      },
      {
        id:'2',
        userName: 'Lily',
        sex:'1',
        state:'1',
        interest:'1',
        birthday:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      }
    ];
    //将数据存入state中保存
    this.setState({
      dataSource:data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request=()=>{
   axios.ajax({
     url:'/table/list1',
     data:{
       params:{
         page:1
       }
     }
   }).then((res)=>{
     if(res.code==0){
       this.setState({
         dataSource2:res.result
       });
     }
   })
  }
  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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'
      }
    ];
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
    );
  }
}

四 表格的loading 处理

拷贝loading.html中的代码+loading.csspublicstyle文件夹下 生成全局的dom 和样式

修改后的index.js如下

<!DOCTYPE html>
<html lang="en">
<!--public/index.html-->
  <head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <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>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

//src/pages/table/basicTable.js
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:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      },
      {
        id:'2',
        userName: 'Lily',
        sex:'1',
        state:'1',
        interest:'1',
        birthday:'2000-01-01',
        address:'北京市海淀区奥林匹克公园',
        time:'09:00'
      }
    ];
    //将数据存入state中保存
    this.setState({
      dataSource:data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request=()=>{
   axios.ajax({
     url:'/table/list1',
     data:{
       params:{
         page:1
       },
       // //  增加下方代码,则不会Loading
       // isShowLoading:false
     }
   }).then((res)=>{
     if(res.code==0){
       this.setState({
         dataSource2:res.result
       });

     }
   })
  };
  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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'
      }
    ];
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
    );
  }
}


//src/axios/index.js
//对jsonp的方法进行封装
import JsonP from "jsonp";//*导入jsonp的插件
import axios from 'axios';//*导入axios插件
import {Modal} from "antd";
//导出一个对象供其他对象进行使用
export default class Axios {
  static jsonp(options) {//定义静态的方法   jsonp  供其他页面进行使用
    return new Promise((resolve, reject) => {//使用Promise解决函数间的嵌套问题   链式调用
      JsonP(options.url, {
        param: 'callback'
      }, function (err, response) {
        //to-do
        //传入JsoP的对象进行操作
        //如果返回的对象是成功,使用resolve方法进行返回
        //debugger;//通过这个打断点
        if (response.status == 'success') {//成功后  用resolve返回数据
          resolve(response);
        } else {    //失败后用reject返回数据
          reject(response.message);
        }
      })
    })
  }

  static ajax(options) {//封装axios   定义为ajax请求,使用Promise
    let loading;
    if(options.data && options.data.isShowLoading !== false){
      loading = document.getElementById('ajaxLoading');
      loading.style.display = 'block';
    }
    const baseApi = 'https://easy-mock.com/mock/5c0893b83b84ee1919884836/mock.api';
    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);
        }
      })
    });
  }
}

五 修改渲染方式,显示对应信息

增加render方法显示对应信息

+ const columns = [ {
        title: '性别',
        dataIndex: 'sex',
        render(sex) {
        return sex == 1 ? '男' : '女'
        }
    }
    ...
    ]

演示

//src/axios/index.js
//对jsonp的方法进行封装
import JsonP from "jsonp";//*导入jsonp的插件
import axios from 'axios';//*导入axios插件
import {Modal} from "antd";
//导出一个对象供其他对象进行使用
export default class Axios {
  static jsonp(options) {//定义静态的方法   jsonp  供其他页面进行使用
    return new Promise((resolve, reject) => {//使用Promise解决函数间的嵌套问题   链式调用
      JsonP(options.url, {
        param: 'callback'
      }, function (err, response) {
        //to-do
        //传入JsoP的对象进行操作
        //如果返回的对象是成功,使用resolve方法进行返回
        //debugger;//通过这个打断点
        if (response.status == 'success') {//成功后  用resolve返回数据
          resolve(response);
        } else {    //失败后用reject返回数据
          reject(response.message);
        }
      })
    })
  }

  static ajax(options) {//封装axios   定义为ajax请求,使用Promise
    let loading;
    if(options.data && options.data.isShowLoading !== false){
      loading = document.getElementById('ajaxLoading');
      loading.style.display = 'block';
    }
    const baseApi = 'https://easy-mock.com/mock/5c0893b83b84ee1919884836/mock.api';
    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
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: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      },
      {
        id: '2',
        userName: 'Lily',
        sex: '1',
        state: '1',
        interest: '1',
        birthday: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      }
    ];
    //将数据存入state中保存
    this.setState({
      dataSource: data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request = () => {
    axios.ajax({
      url: '/table/list1',
      data: {
        params: {
          page: 1
        },
        // //  增加下方代码,则不会Loading
        // isShowLoading:false
      }
    }).then((res) => {
      if (res.code == 0) {
        this.setState({
          dataSource2: res.result
        });

      }
    })
  };

  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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(abc){
          let config = {
            '1':'?‍',
            '2':'?',
            '3':'⚽',
            '4':'?',
            '5':'?',
            '6':'?',
            '7':'?',
            '8':'?',
          };
          return config[abc];
        }
      },
      {
        title: '生日',
        dataIndex: 'birthday'
      },
      {
        title: '地址',
        dataIndex: 'address'
      },
      {
        title: '早起时间',
        dataIndex: 'time'
      }
    ];
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
    );
  }
}


六 在Table 中 嵌套单选按钮

rowSelection

选择功能的配置。 type:“radio” 指定单选

+ const rowSelection = {
  type:'radio'
}
...
+ rowSelection={rowSelection}

对表格中的每个数据,要去添加key

+ data.map((item,index)=>{
+      item.key = index;
+ })
+ const selectedRowKeys = this.state.selectedRowKeys;
+ const rowSelection = {
+   type:'radio',
+    selectedRowKeys
+ }

onRow

通过设置onRow属性,让用户点击Row(行),可以选中Radio(单选)

//src/pages/table/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: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      },
      {
        id: '2',
        userName: 'Lily',
        sex: '1',
        state: '1',
        interest: '1',
        birthday: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      }
    ];
    //动态添加key
    data.map((item,index)=>{
      item.key = index;
    });
    //将数据存入state中保存
    this.setState({
      dataSource: data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request = () => {
    axios.ajax({
      url: '/table/list1',
      data: {
        params: {
          page: 1
        },
        // //  增加下方代码,则不会Loading
        // isShowLoading:false
      }
    }).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() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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(abc){
          let config = {
            '1':'?‍',
            '2':'?',
            '3':'⚽',
            '4':'?',
            '5':'?',
            '6':'?',
            '7':'?',
            '8':'?',
          };
          return config[abc];
        }
      },
      {
        title: '生日',
        dataIndex: 'birthday'
      },
      {
        title: '地址',
        dataIndex: 'address'
      },
      {
        title: '早起时间',
        dataIndex: 'time'
      }
    ];
    const selectedRowKeys = this.state.selectedRowKeys;
    const rowSelection = {
      type:'radio',
      selectedRowKeys
    };
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
    );
  }
}

七 复选按钮

//src/pages/table/basicTable.js
import React from 'react';
import {Card, Table, Modal, Button,message} 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: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      },
      {
        id: '2',
        userName: 'Lily',
        sex: '1',
        state: '1',
        interest: '1',
        birthday: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      }
    ];
    //动态添加key
    data.map((item,index)=>{
      item.key = index;
    });
    //将数据存入state中保存
    this.setState({
      dataSource: data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request = () => {
    axios.ajax({
      url: '/table/list1',
      data: {
        params: {
          page: 1
        },
        // //  增加下方代码,则不会Loading
        // isShowLoading:false
      }
    }).then((res) => {
      if (res.code == 0) {
        res.result.map((item,index)=>{
           item.key = index
        });
        this.setState({//页面刷新,不保留选中字段
          dataSource2: res.result,
          selectedRowKeys:[],
          selectedRows:null
        });

      }
    })
  };

  onRowClick = (record,index)=>{
    let selectKey = [index];
    Modal.info({
      title:'信息',
      content:`用户名:${record.userName},用户爱好:${record.interest}`
    });
    this.setState({
      selectedRowKeys:selectKey,
      selectedItem:record
    })
  };
  //多选执行删除动作
  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();//删除成功,将页面刷新
      }
    })

  });
  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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(abc){
          let config = {
            '1':'?‍',
            '2':'?',
            '3':'⚽',
            '4':'?',
            '5':'?',
            '6':'?',
            '7':'?',
            '8':'?',
          };
          return config[abc];
        }
      },
      {
        title: '生日',
        dataIndex: 'birthday'
      },
      {
        title: '地址',
        dataIndex: 'address'
      },
      {
        title: '早起时间',
        dataIndex: 'time'
      }
    ];
    const selectedRowKeys = this.state.selectedRowKeys;
    const rowSelection = {
      type:'radio',
      selectedRowKeys
    };

    const rowCheckSelection = {
      type:'check',
      selectedRowKeys,
      onChange:(selectedRowKeys,selectedRows)=>{
        this.setState({
          selectedRowKeys,
          selectedRows
        });
      }
    };
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
        <Card title="Mock-复选" style={{margin: '10px 0'}}>
          <div style={{marginBottom:10}}>
            <Button onClick={this.handleDelete}>删除</Button>
          </div>
          <Table
            bordered
            rowSelection={rowCheckSelection}

            columns={columns}
            dataSource={this.state.dataSource2}
            pagination={false}
          />
        </Card>
      </div>
    );
  }
}

八 表格分页

官网的分页组件有些复杂, 要为每个表格添加组件

比较复杂,这里通过封装公共机制进行简化

<Pagination onChange={onChange} total={50} />
参数说明类型默认值
current当前页数number-
defaultCurrent默认的当前页数number1
onChange页码改变的回调,参数是改变后的页码及每页条数Function(page, pageSize)noop

修改 mock api接口

{
  "code": 0,
  "msg": "",
  "result": {
    "list|5": [{
      "id|+1": 1,
      userName: '@cname',
      "sex|1-2": 1,
      "state|1-5": 1,
      "interest|1-8": 1,
      isMarried: "1",
      birthday: '2000-01-01',
      address: '北京市海淀区奥林匹克公园',
      time: '09:00'
    }],
    page: 1,
    page_size: 10,
    total: 100
  }
}
//src/utils/utils.js
export default {
    formateDate(time) {
        if (!time) return '';
        let date = new Date(time);
        return date.getFullYear() + '-' + (date.getMonth() + 1) +
                '-' + date.getDate() + ' ' +
             date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    },
    //封装pagination公共机制
    pagination(data,callback){
        let page = {
            onChange:(current)=>{
                callback(current)
            },
            current:data.result.page,
            pageSize:data.result.page_size,
            total:data.result.total,
            showTotal:()=>{
                return `${data.result.total}`
            },
            showQuickJumper:true
        }
        return page;
    }
}
//src/pages/table/basicTable.js
import React from 'react';
import {Card, Table, Modal, Button,message} from 'antd'
import axios from './../../axios/index';
import Utils from './../../utils/utils'
export default class BasicTable extends React.Component {
  state = {
    dataSource2: []
  };

  params = {
    page:1
  }

  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: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      },
      {
        id: '2',
        userName: 'Lily',
        sex: '1',
        state: '1',
        interest: '1',
        birthday: '2000-01-01',
        address: '北京市海淀区奥林匹克公园',
        time: '09:00'
      }
    ];
    //动态添加key
    data.map((item,index)=>{
      item.key = index;
    });
    //将数据存入state中保存
    this.setState({
      dataSource: data
    });

    this.request();//初始化调用数据
  }

  // 动态获取mock数据
  request = () => {
    let _this = this;
    axios.ajax({
      url: '/table/list1',
      data: {
        params: {
          page: this.params.page
        },
        // //  增加下方代码,则不会Loading
        // isShowLoading:false
      }
    }).then((res) => {
      if (res.code == 0) {
        res.result.list.map((item,index)=>{
           item.key = index
        });
        this.setState({//页面刷新,不保留选中字段
          dataSource2: res.result.list,
          selectedRowKeys:[],
          selectedRows:null,
          pagination:Utils.pagination(res,(current)=>{
            //@todo
            _this.params.page = current;
            _this.request();
          })
        });

      }
    })
  };

  onRowClick = (record,index)=>{
    let selectKey = [index];
    Modal.info({
      title:'信息',
      content:`用户名:${record.userName},用户爱好:${record.interest}`
    });
    this.setState({
      selectedRowKeys:selectKey,
      selectedItem:record
    })
  };
  //多选执行删除动作
  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();//删除成功,将页面刷新
      }
    })

  });
  render() {
    /*title:'id',       展示表头显示内容显示id
      dataIndex:'id'    返回的索引值

      */
    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(abc){
          let config = {
            '1':'?‍',
            '2':'?',
            '3':'⚽',
            '4':'?',
            '5':'?',
            '6':'?',
            '7':'?',
            '8':'?',
          };
          return config[abc];
        }
      },
      {
        title: '生日',
        dataIndex: 'birthday'
      },
      {
        title: '地址',
        dataIndex: 'address'
      },
      {
        title: '早起时间',
        dataIndex: 'time'
      }
    ];
    const selectedRowKeys = this.state.selectedRowKeys;
    const rowSelection = {
      type:'radio',
      selectedRowKeys
    };

    const rowCheckSelection = {
      type:'check',
      selectedRowKeys,
      onChange:(selectedRowKeys,selectedRows)=>{
        this.setState({
          selectedRowKeys,
          selectedRows
        });
      }
    };
    //bordered    配置边框
    //不显示分页     去掉分页
    // +   pagination={false}
    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>
        <Card title="Mock-复选" style={{margin: '10px 0'}}>
          <div style={{marginBottom:10}}>
            <Button onClick={this.handleDelete}>删除</Button>
          </div>
          <Table
            bordered
            rowSelection={rowCheckSelection}

            columns={columns}
            dataSource={this.state.dataSource2}
            pagination={false}
          />
        </Card>

        <Card title="Mock-表格分页" style={{margin: '10px 0'}}>
          <Table
            bordered
            columns={columns}
            dataSource={this.state.dataSource2}
            pagination={this.state.pagination}
          />
        </Card>
      </div>
    );
  }
}


API

Table

参数说明类型默认值
columns表格列的配置描述,具体项见下表ColumnProps[]-

Column#

参数说明类型默认值
dataIndex列数据在数据项中对应的 key,支持 a.b.ca[0].b.c[1] 的嵌套写法string-

经过 Form.create 包装的组件将会自带 this.props.form 属性,this.props.form 提供的 API 如下:

注意:使用 getFieldsValue getFieldValue setFieldsValue 等时,应确保对应的 field 已经用 getFieldDecorator 注册过了。

方法说明类型
getFieldDecorator用于和表单进行双向绑定,详见下方描述
getFieldError获取某个输入控件的 ErrorFunction(name)
getFieldsError获取一组输入控件的 Error ,如不传入参数,则获取全部组件的 ErrorFunction([names: string[]])
getFieldsValue获取一组输入控件的值,如不传入参数,则获取全部组件的值Function([fieldNames: string[]])
getFieldValue获取一个输入控件的值Function(fieldName: string)

rowSelection#

选择功能的配置。

参数说明类型默认值
selectedRowKeys指定选中项的 key 数组,需要和 onChange 进行配合string[][]
onRow设置行属性Function(record, index)
<Pagination onChange={onChange} total={50} />
参数说明类型默认值
current当前页数number-
defaultCurrent默认的当前页数number1
onChange页码改变的回调,参数是改变后的页码及每页条数Function(page, pageSize)noop
pageSize每页条数number-
total数据总数number0
showTotal用于显示数据总量和当前数据顺序Function(total, range)-
showQuickJumper是否可以快速跳转至某页booleanfalse
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值