• 周四. 4月 25th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

react ant table表格切换分页获取全部选中数据

admin

11月 28, 2021

问题: ant 切换页码时,onChange打印selectedRows是能获取当前页的数据,无法获取上一页选中的数据

解决:通过二维数组于页码的组合再转一维数组展示实现

import React, { Component } from 'react';
import { Table, Divider, Modal, message,Button } from 'antd';
import EditForm from '../../components/EditForm';
const { confirm } = Modal;
class TableEdit extends Component {
    state = {
    tableData: [],
    doubleArr: [], // 存放双数组的数组
    filterRows: [], // 存放拼接后的一维数组的变量
        pagination: {
            pageSize: 10,
            current: 1
        },
        loading: false,
        selectedRowKeys: [],
        selectedRows:[],
        columns: [
            {
                title: 'Name',
                dataIndex: 'name'
            },
            {
                title: 'Age',
                dataIndex: 'age'
            },
            {
                title: 'Address',
                dataIndex: 'address'
            },
            {
                title: 'Email',
                dataIndex: 'email'
            },
            {
                title: 'Action',
                dataIndex: 'Action',
                 200,
                align: 'center',
                render: (text, row, index) => (
                    <span>
                        <button className="link-button" onClick={() => this.handleEdit(row)}>
                            编辑
                        </button>
                        <Divider type="vertical" />
                        <button className="link-button" onClick={() => this.handleDel(row)}>
                            删除
                        </button>
                    </span>
                )
            }
        ],
        currentRow: null
    };

    componentWillMount() {
        const { pageSize, current } = this.state.pagination;
        this.fetch(current, pageSize);
    }

    componentWillUnmount() {
        // componentWillMount进行异步操作时且在callback中进行了setState操作时,需要在组件卸载时清除state
        this.setState = () => {
            return;
        };
    }
    // 分页操作
    handleTableChange = (pagination) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        this.setState({ pagination: pager }, () => {
            this.fetch(pager.current, this.state.pagination.pageSize);
        });
    };
    fetch = (pageCurrent, pageSize) => {
        this.setState({ loading: true });
        setTimeout(() => {
            const pager = { ...this.state.pagination };
            pager.total = 100;
            const tableData = [];
            for (let i = (pageCurrent - 1) * pageSize; i < pageSize * pageCurrent; i++) {
                tableData.push({
                    key: i,
                    name: `Edward King ${i}`,
                    age: 32,
                    email: '[email protected]',
                    address: `London, Park Lane no. ${i}`
                });
            }
            this.setState({
                loading: false,
                tableData,
                pagination: pager
            });
        }, 1000);
    };
      // 扁平化二维数组的方法
        mapRows = params => {
            var res = [];
            for (var i = 0; i < params.length; i++) {
                if (Array.isArray(params[i])) {
                    res = res.concat(this.mapRows(params[i]));
                } else {
                    res.push(params[i]);
                }
            }
            return res.filter(Boolean); //去掉undefined的情况
        };
    onSelectedRowChange = (selectedRowKeys, selectedRows) => {
    const { doubleArr, pagination } = this.state
        // 勾选生成二维数组
        doubleArr[pagination.current ? pagination.current - 1 : 0] = selectedRows
        // 这块扁平化成为一位数组
        const filterRows = this.mapRows(doubleArr);
        console.log(filterRows, "filterRows") // 这块可以打印出来拼接的结果
        this.setState({
          selectedRowKeys: selectedRowKeys,
          selectedRows: filterRows // 存放拼接好的一维数组
        });
  };
    // 编辑
    handleEdit(row) {
        this.setState({ currentRow: row, visible: true });
    }
    // 删除
    handleDel(row) {
        confirm({
            title: '温馨提示',
            content: '确定要删除当前内容吗?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                message.info('你点击了确定,当前行key为:' + row.key, 1);
            },
            onCancel() {}
        });
    }
    handleOk = () => {
        this.setState({ visible: false });
    };

    handleCancel = () => {
        this.setState({ visible: false });
    };
    // 提交
    handleSubmit = e => {
        e.preventDefault();
        let _this = this;
        this.formRef.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                this.setState({ visible: false });
                // 此处应该为后台业务逻辑
                setTimeout(() => {
                    Modal.info({
                        title: '点击了提交',
                        content: (
                            <div>
                                <p>当前表单内容为:</p>
                                <p>{JSON.stringify(values)}</p>
                            </div>
                        ),
                        onOk() {
                            // 操作完跳转到第一页
                            const pager = { ..._this.state.pagination };
                            pager.current = 1;
                            _this.setState({ pagination: pager });
                            _this.fetch(1, _this.state.pagination.pageSize);
                            // console.log(_this.state.selectedRowKeys)
                        }
                    });
                }, 500);
            }
        });
    };
    getAllSel=()=>{
        console.log(this.state.selectedRowKeys,this.state.selectedRows)
    }
    render() {
        const { selectedRowKeys, loading, pagination, columns, tableData } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectedRowChange
        };
        return (
            <div className="shadow-radius">
            <Button onClick={this.getAllSel}>获取选中数据</Button> <br/>
            <br/>
                <Table
                    bordered
                    columns={columns}
                    dataSource={tableData} // list数据
                    loading={loading}
                    onChange={this.handleTableChange}
                    pagination={pagination}
                    rowSelection={rowSelection}
                />
                <Modal title="编辑信息" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} footer={null}>
                    <EditForm data={this.state.currentRow} visible={this.state.visible} wrappedComponentRef={form => (this.formRef = form)} handleSubmit={this.handleSubmit} />
                </Modal>
            </div>
        );
    }
}

export default TableEdit;

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注