基于antd-react自定义导出标题功能需求

2020-07-20  本文已影响0人  甘道夫老矣

自己研究出来满足当前需求的功能,研究不宜,觉得好给个赞吧

需求:标题可以自己选择,并且还能自己排序,标题还可以自己定义
提供:所有的标题,导出的数据(为解析的),react+antd(4.0)+file-saver
代码:

//需要安装拖拽的node包:array-move,react-sortable-hoc
import React, { Component } from "react";
import { Route, Link, Switch, Redirect } from "react-router-dom";
import { Table, Row, Col, Button, Modal, Input, message, Select } from "antd";

//下面的都是拖拽需要的
import { sortableContainer, sortableElement, sortableHandle } from "react-sortable-hoc";
import { MenuOutlined } from "@ant-design/icons";
import arrayMove from "array-move";
const DragHandle = sortableHandle(() => <MenuOutlined style={{ cursor: "pointer", color: "#999" }} />);
const SortableItem = sortableElement((props) => <tr {...props} />);
const SortableContainer = sortableContainer((props) => <tbody {...props} />);
const DragableBodyRow = ({ index, className, style, ...restProps }) => <SortableItem index={restProps["data-row-key"]} {...restProps} />;

//导入service
import * as listService from "../service/asset.card.list.service";
//封装的方法,导出使用
import ExportExcel from "../components/ExportExcel";

const { Option } = Select;
export default class AssetCardList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //标题数据
            titleData: [
                {
                    key: "1",
                    title: "资产名称", //必须要
                    dataIndex: "aiName", //必须要
                    index: 0, //必须要
                },
                {
                    key: "2",
                    title: "价值类型",
                    dataIndex: "aiVaty",
                    index: 1,
                },
                {
                    key: "3",
                    title: "经费来源",
                    dataIndex: "aiFufr",
                    index: 2,
                },
                {
                    key: "4",
                    title: "项目预算标号",
                    dataIndex: "aiProj",
                    index: 3,
                },
                {
                    key: "5",
                    title: "使用部门",
                    dataIndex: "aiUdid",
                    index: 4,
                },
                {
                    key: "5",
                    title: "管理人",
                    dataIndex: "aiMpid",
                    index: 5,
                },
                {
                    key: "6",
                    title: "销售商",
                    dataIndex: "销售商",
                    index: 6,
                },
            ],
            //表格数据
            dataSource: [],
            //获取来的数据
            data: [
                { aiName: "当当", aiVaty: "自定义", aiUdid: "财务部" },
                { aiName: "朵朵", aiVaty: "规定", aiUdid: "门市部" },
                { aiName: "当当2", aiVaty: "评估", aiUdid: "人事部" },
            ],

            ModalVisible: false,
            record: null,
            inputValue: null,
        };
    }

    async componentDidMount() {
        this.getTableData();
    }

    //获取表格数据
    getTableData = async () => {
        let res = await listService.selectAssetData();

        if (res.statusCode !== 0) return message.info(res.message);
        let arrs = res.result.nodes;

        arrs.forEach((item, index, arr) => {
            if (item.aiGode.length > 0) {
                item.aiGode.forEach((items) => {
                    let obj = {};
                    obj[items.piName] = items.piMsg;
                    Object.assign(item, obj);
                });
            }
        });
        console.log(arrs);

        this.setState({
            data: arrs,
        });
    };

    //拖拽方法
    onSortEnd = ({ oldIndex, newIndex }) => {
        const { dataSource } = this.state;
        if (oldIndex !== newIndex) {
            const newData = arrayMove([].concat(dataSource), oldIndex, newIndex).filter((el) => !!el);
            console.log(newData);
            this.setState({ dataSource: newData });
        }
    };

    //编辑
    handleEdit = (record) => {
        this.setState({
            ModalVisible: true,
            record,
        });
    };

    //选择 添加字段
    handleChange = (value, option) => {
        const { titleData } = this.state;
        let newArr = [];
        option.forEach((item, indexs) => {
            let obj = {};
            obj.index = indexs;
            obj.title = item.value;
            obj.dataIndex = item.key;
            obj.key = (indexs + 1).toString();
            newArr.push(obj);
        });
        this.setState({
            dataSource: newArr,
        });
        //console.log(newArr);
    };

    //弹出框按钮
    handleOk = () => {
        let { dataSource, record } = this.state;
        let res = this.inputValue.state.value.replace(/\s+/g, "");
        if (!res) {
            message.info("名称不能为空");
            return;
        }
        dataSource.forEach((item) => {
            if (record.key === item.key) {
                item.title = res;
            }
        });
        this.setState({
            ModalVisible: false,
            record: null,
        });
    };
    handleCancel = () => {
        this.setState({
            ModalVisible: false,
            record: null,
        });
    };

    //点击导出
    handleUpload = () => {
        let { dataSource, data } = this.state;

        let newArr = [],
            keyValue = {};
        dataSource.forEach((item) => {
            keyValue[item.dataIndex] = "1";
        });
        newArr = data.map((item) => {
            let currdata = {};
            Object.keys(item).forEach((key) => {
                if (keyValue[key]) {
                    currdata[key] = item[key];
                }
            });
            return currdata;
        });
        console.log(dataSource);

        newArr.forEach((item) => {
            for (let index in item) {
                if (item[index] === null || item[index] === undefined || JSON.stringify(item[index]) === "{}") {
                    item[index] = "";
                }
                //判断是不是字符串

                if (item[index] && typeof item[index] == "string" && item[index].constructor == String && item[index].toString().indexOf(",") > -1) {
                    item[index] = item[index].replace(/,/g, "、");
                }

                //使用部门
                if (index === "aiUdid") {
                    let res = "";
                    item[index].forEach((items, index) => {
                        res += items.osName;
                    });
                    item[index] = res;
                }

                //资产分类
                if (index === "aiAsco") {
                    let res = "";
                    item[index].forEach((items, index) => {
                        res += items.caName;
                    });
                    item[index] = res;
                }

                //object
                if (item[index] instanceof Object && item[index].label) {
                    item[index] = item[index].label;
                }
            }
        });
        console.log(newArr);
                //调用导出的方法
        ExportExcel(dataSource, newArr);
    };

    render() {
        const { dataSource, ModalVisible, record, titleData } = this.state;
        const columns = [
            {
                title: "拖拽",
                dataIndex: "sort",
                align: "center",
                width: 62,
                render: () => <DragHandle />,
            },
            {
                title: "序号",
                align: "center",
                dataIndex: "key",
            },
            {
                title: "标题",
                align: "center",
                dataIndex: "title",
            },
            {
                title: "操作",
                align: "center",
                dataIndex: "operation",
                render: (text, record) => {
                    return (
                        <div>
                            <a
                                onClick={() => {
                                    this.handleEdit(record);
                                }}
                            >
                                编辑
                            </a>
                        </div>
                    );
                },
            },
        ];

        const DraggableContainer = (props) => <SortableContainer useDragHandle helperClass="row-dragging" onSortEnd={this.onSortEnd} {...props} />;

        return (
            <div className="main-box">
                <Select
                    placeholder="请选择导出的字段"
                    mode="multiple"
                    //   defaultValue={['a10', 'c12']}
                    onChange={this.handleChange}
                    // onSelect={this.onSelect}
                    style={{ width: "100%" }}
                >
                    {titleData.length > 0 &&
                        titleData.map((item, index) => {
                            return (
                                <Option value={item.title} key={item.dataIndex}>
                                    {item.title}
                                </Option>
                            );
                        })}
                </Select>
                <Button onClick={this.handleUpload} style={{ margin: " 20px 0" }}>
                    点击导出
                </Button>
                {dataSource && (
                    <Table
                        pagination={false}
                        dataSource={dataSource}
                        columns={columns}
                        rowKey={(record) => record.index}
                        bordered
                        components={{
                            body: {
                                wrapper: DraggableContainer,
                                row: dataSource.length > 0 ? DragableBodyRow : null,
                            },
                        }}
                    />
                )}

                {record && (
                    <Modal title="编辑" visible={ModalVisible} onOk={this.handleOk} destroyOnClose={true} onCancel={this.handleCancel}>
                        <Input placeholder="请编辑名称" ref={(val) => (this.inputValue = val)} />
                    </Modal>
                )}
            </div>
        );
    }
}

上一篇 下一篇

猜你喜欢

热点阅读