react笔记之学习之完成删除功能

简介: react笔记之学习之完成删除功能

前言

我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷 微信公众号前端小歌谣 关注公众号带你进入前端学习交流群

image.png

代码案例LogItem.js

import React, { useState, useEffect, useCallback, memo } from 'react';
import {
    Modal,
    Input,
    message,
    Form,
    Select,
    Table,
    Button,
    Row,
    Col,
    Card,
    DatePicker,
    Cascader,
    Tabs,
    Typography, InputNumber
} from 'antd';
import { Menu } from '../service';
import {
    useQueryOrderDetailMutation, useManufactureAddMutation
} from '@/restapi/service/order/order'
import {
    useLazyQueryBaseCustomerQuery,
    useLazyQueryCategoryListQuery, useLazyQueryColorTypeListQuery, useLazyQuerySizeTypeListQuery,
    useLazyQueryStyleDataListQuery
} from "@/restapi/service/commonselect/tablerestapi";
import styles from "./indexOrder.module.less";
import { SingleValueType } from 'rc-cascader/lib/Cascader';
import { useQueryRegionListMutation } from "@/restapi/service/factory/factory";
import moment from "moment";
import { useNavigate } from "react-router";
const { Option } = Select
const { TabPane } = Tabs;
interface AddOrEditMenuFormProps {
    id?: number;
}
export interface AddOrEditMenuProps {
    visible: boolean;
    menu: Menu | null;
    onClose: () => void;
    onConfirm: (obj: any) => void;
    list: any[]
}
type ListItemType = {
    code?: string | number;
    id?: string;
    name?: string;
}
interface Option {
    id?: string;
    name?: string;
    children?: Option[];
}
const isEditing = (record: any) => {
    return record.editable;
};
type ValueType = SingleValueType | SingleValueType[]
const AddScModel: React.FC<any> = (props) => {
    const { addData } = props
    const navigate = useNavigate()
    const [form] = Form.useForm();
    const [formKuan] = Form.useForm();
    const [data, setData] = useState<any>([]); //存放表格内容
    const [disFlag, setDisFlag] = useState<boolean>(false)
    const [region, setRegion] = useState<Array<Option>>()
    const [regionData, setRegionData] = useState<ValueType>()
    const [customeList, setCustomList] = useState<ListItemType[]>([])
    const [styleList, setStyleList] = useState<Array<ListItemType>>([])
    const [styleList2, setStyleList2] = useState<Array<ListItemType>>([])
    //存储数据
    const [styleList3, setStyleList3] = useState<Array<ListItemType>>([])
    const [sizeList, setSizeList] = useState<ListItemType[]>([])
    const [getStyle, setGetStyle] = useState<any>("");
    const [queryBaseCustomer] = useLazyQueryBaseCustomerQuery();
    const [queryRegionList] = useQueryRegionListMutation()
    const [queryCategoryList] = useLazyQueryCategoryListQuery()
    const [queryColorList] = useLazyQueryColorTypeListQuery()
    const [querySizeList] = useLazyQuerySizeTypeListQuery()
    const [queryOrderDetailList] = useQueryOrderDetailMutation()
    const [queryStyleDataList] = useLazyQueryStyleDataListQuery()
    const [manufactureAdd] = useManufactureAddMutation()
    const [activeKey, setActiveKey] = useState<string>();
    const [editingKey, setEditingKey] = useState("");
    const columnsTab = [
        {
            title: '颜色',
            dataIndex: 'colorId',
            width: 300,
            editable: false,
            componentType: 'select',
            message: '请输入颜色',
            render: (text: any) => {
                return getColor(text)
            }
        },
        {
            title: '尺码',
            editable: false,
            dataIndex: 'sizeId',
            width: 300,
            componentType: 'select',
            message: '请输入尺码',
            render: (text: any) => {
                return getSize(text)
            }
        },
        {
            title: '合同数量',
            editable: false,
            dataIndex: 'ordCount',
            width: 300,
            componentType: 'input',
            message: '请输入合同数量'
        },
        {
            title: '生产数量',
            editable: true,
            dataIndex: 'count',
            width: 300,
            componentType: 'input',
            message: '请输入生产数量'
        },
        {
            title: '操作',
            dataIndex: '',
            width: 300,
            fixed: 'right',
            render: (text: any, record: any, index: number) => {
                // 判断是否进入编辑状态
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a
                            onClick={() => save(record.id, record)}
                            style={{
                                marginRight: 8
                            }}
                        >
                            保存
                        </a>
                        <a onClick={() => cancel(record.id)}>取消</a>
                    </span>
                ) : (
                    <div>
                        <Typography.Link
                            disabled={editingKey !== ""}
                            onClick={() => edit(record)}
                        >
                            编辑
                        </Typography.Link>
                        <Button type="link" onClick={() => delInfo(record, index)}>删除</Button>
                    </div>
                );
            }
        }
    ]
    //行编辑
    const getColor = (value: any) => {
        let text: any = ''
        styleList.forEach((item) => {
            if (value == item.id) {
                text = item.name
            }
        })
        return text
    }
    const getSize = (value: any) => {
        let text: any = ''
        sizeList.forEach((item) => {
            if (value == item.id) {
                text = item.name
            }
        })
        return text
    }
    const delInfo = useCallback((record: any, index: number) => {
        console.log(record, index, "data")
        const list = [...data]
        console.log(list)
        list.splice(index, 1)
        setData(list)
    }, [data])
    const save = async (key: any, record: any) => {
        try {
            const row: any = await formKuan.validateFields();
            if (record.ordCount < row.count) {
                message.warning('生产数量不能大于合同数量,请重新输入!')
                return false
            }
            const newData = [...data];
            const index = newData.findIndex((item: any) => key === item.id);
            if (index > -1) {
                const item: any = newData[index];
                item.editable = false;
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey("");
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey("");
            }
        } catch (errInfo) {
            console.log("保存失败", errInfo);
        }
    };
    const edit = async (record: any) => {
        formKuan.setFieldsValue({
            editable: true,
            ...record
        });
        setEditingKey(record.id);
        //切换成编辑状态
        const newData: any = [...data];
        const index = newData.findIndex((item: any) => record.id === item.id);
        if (index > -1) {
            const item = { ...newData[index], editable: true };
            newData.splice(index, 1, { ...item });
            setData(newData)
        }
    };
    const cancel = (id: any) => {
        const newData = [...data];
        const index = newData.findIndex((item: any) => id === item.id);
        if (index > -1) {
            const item: any = newData[index];
            item.editable = false;
            newData.splice(index, 1, { ...item });
            setData(newData);
            setEditingKey("");
        }
    };
    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }: {
        editing: any,
        dataIndex: any,
        title: any,
        inputType: any,
        record: any,
        index: any,
        children: any
    }) => {
        const inputNode = <InputNumber min={1} style={{ width: "300px" }} autoComplete="off" />
        const selectNode = dataIndex == 'sizeId' ? <Select
            style={{ width: "300px" }}
            placeholder="请选择尺寸"
            optionFilterProp="children"
        >
            {sizeList && sizeList.map((item: any) => (
                <Option value={item.id}>{item.name}</Option>
            ))}
        </Select> : <Select
            style={{ width: "300px" }}
            placeholder="请选择颜色"
            optionFilterProp="children"
        >
            {styleList && styleList.map((item: any) => (
                <Option value={item.id}>{item.name}</Option>
            ))}
        </Select>
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0
                        }}
                        rules={[
                            {
                                required: false,
                                message: `请输入${title}!`
                            }
                        ]}
                    >
                        {inputType == 'input' ? inputNode : selectNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    // 依据是否可编辑返回不同元素
    const mergedColumns = columnsTab.map((col: any) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: any) => ({
                record,
                inputType: col.componentType,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });
    const onOk = () => {
        if (data.length == 0) {
            message.warning('请添加款式!')
        } else {
            form.validateFields().then(res => {
                console.log(res, "res")
                const values = res
                const info: any = {
                    ...values,
                };
                console.log(info, "info")
                if (info.id) {
                } else {
                    info.orderId = form.getFieldValue("id")
                    info.itemList = data.filter((item: any) => {
                        return item.styleId === getStyle
                    })
                    manufactureAdd(info)
                        .unwrap()
                        .then((response: any) => {
                            if (response.code === 200) {
                                // navigate("/productionOrder")
                                message.success('添加成功')
                            }
                        });
                }
            });
        }
    }
    const onClose = () => {
        form.resetFields()
        props.onClose()
    };
    useEffect(() => {
        querySizeList("t_sys_institution")
            .unwrap()
            .then((response: any) => {
                console.log(response, "response")
                let arr: ListItemType[] = []
                response.data && response.data.map((item: any) => {
                    arr.push({ code: item.code, id: item.id, name: item.name })
                })
                console.log(arr, "arr")
                setSizeList(arr)
            });
    }, [])
    //查看款式得接口
    useEffect(() => {
        queryColorList("")
            .unwrap()
            .then((response: any) => {
                if (response.code === 200) {
                    let arr: ListItemType[] = []
                    response.data && response.data.map((item: any) => {
                        arr.push({ code: item.code, id: item.id, name: item.name })
                    })
                    setStyleList(arr)
                }
            });
    }, []);
    //查看省市区的接口
    useEffect(() => {
        queryRegionList("/style/type/getComboBox")
            .unwrap()
            .then((response: any) => {
                if (response.code === 200) {
                    setRegion(response.data)
                }
            });
    }, []);
    //查看款式
    useEffect(() => {
        queryBaseCustomer("t_sales_order")
            .unwrap()
            .then((response: any) => {
                console.log(response, "response")
                let arr: ListItemType[] = []
                response.data && response.data.map((item: any) => {
                    arr.push({ code: item.code, id: item.id, name: item.name })
                })
                setCustomList(arr)
            });
    }, [])
    const setFormValue = (value: any) => {
        form.setFieldsValue({
            ...value,
            areaAll: [value.province, value.city, value.area]
        })
    }
    const queryDetail = (obj: any) => {
        queryOrderDetailList({ orderId: obj.id })
            .unwrap()
            .then((response: any) => {
                if (response.code == 200) {
                    let arr: ListItemType[] = []
                    const list: any = [...response.data.typeList]
                    list && list.map((item: any) => {
                        arr.push({ code: item.code, id: item.styleId, name: item.styleName })
                    })
                    setStyleList2(arr)
                    setStyleList3(arr)
                    const newDate = [...response.data.itemList]
                    setData(
                        newDate.map((item: any) => {
                            return { ...item, editable: false, ordCount: item.count }
                        })
                    )
                    setActiveKey(arr[0].id)
                }
            })
            ;
    }
    const makeStyle = (value: any) => {
        setGetStyle(value)
    }
    const remove = (targetKey: string) => {
        let newActiveKey = activeKey;
        let lastIndex = -1;
        styleList2.forEach((item, i) => {
            if (item.id == targetKey) {
                lastIndex = i - 1;
            }
        });
        console.log(lastIndex, "lastIndex")
        const newPanes = styleList2.filter(item => item.id != targetKey);
        if (newPanes.length > 0) {
            setStyleList2(newPanes);
            setActiveKey(newPanes[0].id);
        } else {
            setStyleList2([]);
            setActiveKey("");
        }
        // console.log([...data].filter((item: any) => {
        //     return targetKey != item.styleId
        // }), targetKey)
        // setData([...data].filter((item: any) => {
        //     return targetKey != item.styleId
        // }))
        // console.log(newPanes,"newPanes")
        // setStyleList2(newPanes);
        // setActiveKey(newActiveKey);
    };
    const onChange = (newActiveKey: string) => {
        console.log(data, "data")
        setActiveKey(newActiveKey);
    };
    const onEdit = (targetKey: any, action: 'add' | 'remove') => {
        if (action === 'add') {
            // add();
        } else {
            remove(targetKey);
        }
    };
    useEffect(() => {
        const dataObj = { ...props.addData }
        dataObj.planDate = moment(dataObj.planDate)
        setFormValue(dataObj)
        queryDetail(props.addData)
        console.log(props)
    }, [props.addData])
    const handleRecover = () => {
        setStyleList2(styleList3)
        setActiveKey(styleList3[0].id)
    }
    console.log(addData,"addDataaddDataaddData")
    return (
        <div>
            <div className={styles['fontFlag']}>
                基本信息
            </div>
            <Card style={{ marginTop: "20px" }}>
                <Row style={{ marginTop: "20px" }} gutter={24}>
                    <Col span={6}>
                        客户名称:{addData?.customerName}
                    </Col>
                    <Col span={6}>
                        订单号:{addData?.orderCode}
                    </Col>
                    <Col span={6}>
                        合同号:{addData?.contractNumber}
                    </Col>
                    {/* <Col span={6}>
                        交货日期:{croppData?.plan_date}
                    </Col> */}
                    {/* <Col span={6}>
                        款式名称:{croppData?.style_name}
                    </Col> */}
                    {/* <Col span={6}>
                        款式编码:{croppData?.style_number}
                    </Col> */}
                </Row>
            </Card>
            {/* <Card className={styles['marginTen']}>
                <Form
                    disabled
                    form={form}
                    labelCol={{
                        sm: { span: 5 },
                    }}
                    wrapperCol={{
                        sm: { span: 16 },
                    }}
                >
                    <Row gutter={24}>
                        <Col span={7}>
                            <Form.Item
                                label="客户名称"
                                name="customerId"
                                rules={[{ required: false, message: '请输入客户名称' }]}
                            >
                                <Select
                                    showSearch
                                    style={{ width: 200 }}
                                    placeholder="请输入客户名称"
                                    optionFilterProp="children"
                                >
                                    {customeList && customeList.map((item: any) => (
                                        <Option value={item.id}>{item.name}</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={7}>
                            <Form.Item
                                label="合同号"
                                name="contractNumber"
                                rules={[{ required: false, message: '请输入合同号' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={7}>
                            <Form.Item
                                label="订单编号"
                                name="orderCode"
                                rules={[{ required: false, message: '请输入订单编号' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Card> */}
            <div className={styles['kuanFlag']}>
                <div>
                    款式信息
                </div>
            </div>
            <div className={styles['kuanFlag']}>
                <Button onClick={handleRecover} type='primary'>恢复</Button>
            </div>
            <div className={styles['marginTopHeight']}>
                {/* <Select
                    style={{ width: 200 }}
                    placeholder="请选择所属款式"
                    optionFilterProp="children"
                    key={getStyle}
                    defaultValue={getStyle}
                    onChange={makeStyle}
                >
                    {styleList2 && styleList2.map((item: any) => (
                        <Option value={item.id}>{item.name}</Option>
                    ))}
                </Select> */}
                <Tabs
                    hideAdd
                    onChange={onChange}
                    activeKey={activeKey}
                    type="editable-card"
                    onEdit={onEdit}
                >
                    {styleList2 && styleList2.map((pane, index) => (
                        <TabPane closable tab={pane.name} key={pane.id}>
                        </TabPane>
                    ))}
                </Tabs>
            </div>
            <div className={styles['marginBack']}>
                <Form form={formKuan} component={false}>
                    <Table
                        className="user-table"
                        rowKey="id"
                        components={{
                            body: {
                                cell: EditableCell
                            }
                        }}
                        dataSource={data.filter((item: any) => item.styleId == activeKey)}
                        columns={mergedColumns}
                        pagination={false}
                        summary={data => {
                            let totalCount = 0;
                            data.forEach((item: any) => {
                                if (item.styleId === activeKey) {
                                    totalCount += parseInt(item.count);
                                }
                            });
                            return (
                                <>
                                    <Table.Summary.Row>
                                        <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
                                        <Table.Summary.Cell index={1}>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={2}>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={3}>
                                            <span>{totalCount}</span>
                                        </Table.Summary.Cell>
                                    </Table.Summary.Row>
                                </>
                            );
                        }}
                    />
                </Form>
            </div>
            <Card>
                <div className={styles['bottomBtn']}>
                    <Button onClick={onClose} className={styles['kuanButtonContent']}>取消</Button>
                    <Button type={"primary"} className={styles['kuanButtonContent']} onClick={onOk}>保存</Button>
                </div>
            </Card>
        </div>
    );
}
export default memo(AddScModel);
相关文章
|
2月前
|
前端开发 JavaScript
React学习之——条件渲染
【10月更文挑战第16天】React 中没有像Vue中v-if这种指令。React 中的条件渲染和 JavaScript 中的一样,使用 JavaScript 运算符 if 或者条件运算符去创建元素来表现当前的状态,然后让 React 根据它们来更新 UI。
|
3月前
|
前端开发 JavaScript
学习react基础(3)_setState、state、jsx、使用ref的几种形式
本文探讨了React中this.setState和this.state的区别,以及React的核心概念,包括核心库的使用、JSX语法、类与函数组件的区别、事件处理和ref的使用。
91 3
学习react基础(3)_setState、state、jsx、使用ref的几种形式
|
3月前
|
前端开发
学习react基础(2)_props、state和style的使用
本文介绍了React中组件间数据传递的方式,包括props和state的使用,以及如何在React组件中使用style样式。
42 0
|
2月前
|
移动开发 前端开发 JavaScript
React DnD:实现拖拽功能的终极方案?
本文首发于微信公众号“前端徐徐”,介绍了一个强大的 React 拖拽库——React DnD。React DnD 帮助开发者轻松创建复杂的拖拽界面,适用于 Trello 风格的应用、列表重排序、可拖拽的 UI 组件等场景。文章详细介绍了 React DnD 的基本信息、主要特点、使用场景及快速上手指南。
187 3
React DnD:实现拖拽功能的终极方案?
|
1月前
|
前端开发 JavaScript 安全
学习如何为 React 组件编写测试:
学习如何为 React 组件编写测试:
41 2
|
2月前
|
资源调度 前端开发 JavaScript
React进阶学习
React进阶学习
17 1
|
3月前
|
移动开发 前端开发
react项目配合diff实现文件对比差异功能
在React项目中,可以使用`diff`库实现文件内容对比差异功能。首先安装`diff`库,然后在组件中引入并使用`Diff.diffChars`或`Diff.diffLines`方法比较文本差异。通过循环遍历`diff`结果,可以生成不同样式的HTML元素来高亮显示文本差异。
164 1
react项目配合diff实现文件对比差异功能
|
3月前
|
XML JavaScript 前端开发
学习react基础(1)_虚拟dom、diff算法、函数和class创建组件
本文介绍了React的核心概念,包括虚拟DOM、Diff算法以及如何通过函数和类创建React组件。
38 3
|
2月前
|
JSON 前端开发 JavaScript
React 进阶阶段学习计划
React 进阶阶段学习计划
|
3月前
|
前端开发
React 中购物车功能实现(全选多选功能实现)
React 中购物车功能实现(全选多选功能实现)
47 2