react的表头可配置化

实现效果:

Table上面增加一个按钮,按钮触发一个Model页面,里面是checkBox组件,提供表头字段的选择。

选中那个字段,table呈现那个字段。

import React from 'react';
import {Table,Checkbox,Button,Modal, Row, Col, Card} from 'antd';
import {sessionCheck} from '../../axios';
import axios from 'axios';
import * as config from '../../axios/config';
import BreadcrumbCustom from '../BreadcrumbCustom';
import ModelSearch from '../search/ModelSearch'
import {message} from "antd/lib/index";
import moment from "moment/moment";
// import CarPhotoEditForm from '../preliminary/CarPhotoEditForm';


const listPlan = (pagination, searchParam) => axios.get(config.HOST + '/carModel/modelList', {
    params: {
        userToken: JSON.parse(localStorage.getItem('user')).token,
        step: 320,
        pageNumber: pagination.current,
        pageSize: 10,
        series_id: searchParam?searchParam.series_id:null,
        model_id: searchParam?searchParam.model_id:null,
        model_name: searchParam?searchParam.model_name:null,
    }
}).then(function (response) {
    return response.data;
}).catch(function (error) {
    console.log(error);
});
/*从systemTableColumn表中获取表的每一字段的信息*/
const listColsByTable = () => axios.get(config.HOST + '/systemTableColumn/listColsByTable', {
    params: {
        userToken: JSON.parse(localStorage.getItem('user')).token,
        tablename:'car300carmodel'
    }
}).then(function (response) {
    return response.data;
}).catch(function (error) {
    console.log(error);
});

class CarBrand extends React.Component {

    state = {
        loading: false,
        pagination: {},
        searchForm: null,
        searchParam: {},
        data: [],

        checkBoxs:[], /*  表头编辑框里面展示的数据 */
        ColumnVisible :false, /*  表头编辑框是否可见  */
        columns:[],/*  table的一个props   */
        colobjs:[],/*  table的每个字段的详细信息,从数据库里面获取到的  */
        cols:[]/*  table展示的col的English的名字的数组  */
    };

    componentDidMount() {
        this.start();
    }

    start = (currenPage, searchParam) => {
        const router = this.props.router;
        const pager = {...this.state.pagination};
        if (currenPage) {
            pager.current = currenPage;
        }
        this.setState({loading: true});
        listPlan(pager, searchParam).then(res => {
            if (!sessionCheck(router, res)) {
                return;
            }
            if (!res || !res.pager) {
                return;
            }

            const pagination = {};
            pagination.total = res.pager.totalCount;
            pagination.current = res.pager.pageNumber;

            this.setState({
                pagination: pagination,
            });
            res && res.data && this.setState({
                data: res.data,
                loading: false
            });
        });

        /*配置的信息保存在 this.state.colobjs */
        listColsByTable().then(res=>{
            if (!sessionCheck(router, res)) {
                return;
            }
            /*最初始的cols*/
            let cols=res.data.map((obj)=>obj.column)
            res && res.data && this.setState({
                cols:cols,
                colobjs: res.data,
                loading: false
            });
            this.colChange(cols)
        })


    };
    refSearchForm = (form) => {
        this.searchForm = form;
    };
    handleSearch = (e) => {
        const form = this.searchForm;
        e.preventDefault();
        form.validateFields((err, values) => {
            this.setState({searchParam: values});
            const pagination = {};
            listPlan(pagination, values).then(res => {
                const pagination = {};
                pagination.total = res.pager.totalCount;
                pagination.current = res.pager.pageNumber;

                this.setState({
                    pagination: pagination,
                });

                res && res.data && this.setState({
                    data: res.data,
                    loading: false
                });
            });
        });
    };
    handleTableChange = (pagination, filters, sorter) => {
        this.start(pagination.current, this.state.searchParam);
    };
    /*CheckBox的配置界面的生成*/
    setParam=()=>{
        let AllCheckBoxs=this.state.colobjs.map((colobj)=>colobj.column)
        let checkBoxs=[]
        checkBoxs=AllCheckBoxs.map((v)=>{
            let t
            this.state.colobjs.forEach((n)=>{
                if(n.column===v){
                    t= n.cnname
                }
            })
            return (
                <Col span={8}><Checkbox  value={v}>{t}</Checkbox></Col>
            )

        })
        this.setState({
            checkBoxs: checkBoxs,
            ColumnVisible:true ,

        });


    }
    /*隐藏表头编辑框*/
    hideModal = () => {
        this.setState({
            ColumnVisible: false,
        });
    }
    /*针对每次传入的cols生成新的columns*/
    colChange=(cols)=>{
        let columns=[]
        cols.map((v,op)=>{
            let t
            let type
            this.state.colobjs.forEach((n)=>{
                if(n.column===v){
                    t= n.cnname
                    type=n.type
                }
            })
            if(type==='datetime'){
                columns.push(
                    {
                        title: t,
                        dataIndex: v,
                        key: 'k'+op,
                        width: 40,
                        render:(text, record)=>{
                            let t=moment(parseInt(text,10))
                            return t.format('YYYY-MM-DD')
                        }
                    }
                )
            }
            if(!type){
                columns.push(
                    {
                        title: t,
                        dataIndex: v,
                        key: 'k'+op,
                        width: 40,
                    }
                )
            }

            return null
        })
        if(columns.length===0){
            message.success('请至少选中一项!',5);
        }
        this.setState({
            cols:cols,
            columns:columns
        });
    }

    render() {
        const columns = this.state.columns;

        return (
            <div className="gutter-example">
                <BreadcrumbCustom first="车辆信息查询" second="车型列表"/>
                <Card bordered={false}>
                    <ModelSearch refSearchForm={this.refSearchForm}  handleSearch={this.handleSearch}/>
                </Card>
                <Modal
                    title="筛选"
                    visible={this.state.ColumnVisible}
                    onCancel={this.hideModal}
                    footer={[
                        <Button key="back" size="large" onClick={this.hideModal}>确认</Button>,
                    ]}
                >
                    <Checkbox.Group style={{ width: '100%' }} defaultValue={this.state.cols} onChange={this.colChange}>
                        <Row>
                            {this.state.checkBoxs}
                        </Row>
                    </Checkbox.Group>
                </Modal>
                <Row gutter={16}>
                    <Col className="gutter-row" md={24}>
                        <div className="gutter-box">
                            <Card bordered={false}>
                                <div>
                                    <Button   type="primary" onClick={this.setParam}>筛选</Button>
                                    <Table
                                           columns={columns}
                                           dataSource={this.state.data}
                                           pagination={
                                               {  //分页
                                                   total:this.state.pagination.total, //数据总数量
                                                   current:this.state.pagination.current,
                                                   pageSize:10,  //显示几条一页
                                                   showTotal: () =>{  //设置显示一共几条数据
                                                       console.log("数据总数:",this.state.pagination)
                                                       return '共 ' +this.state.pagination.total+ ' 条数据';
                                                   },
                                               }
                                           }
                                           onChange={this.handleTableChange}
                                          />

                                </div>

                            </Card>
                        </div>
                    </Col>
                </Row>
            </div>
        );
    }
}

export default CarBrand;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值