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);
相关文章
|
24天前
|
前端开发 API UED
怎么学习React 18 进行项目开发?
【4月更文挑战第18天】学习React 18涉及新特性如并发模式、Suspense API和自动批处理更新,可提升性能和用户体验。首先了解这些新特性,然后掌握React基础知识,如组件化、JSX、props和state。使用Create React App创建项目,学习如何启用并发模式和使用Suspense显示占位符。实现自定义组件,关注props传递、状态管理和事件处理。通过Profiler优化性能,利用懒加载和代码分割减少加载时间,使用Context API共享状态。不断实践和探索,参考官方文档与社区资源,以提高开发技能。
101 3
|
1月前
|
前端开发 JavaScript API
如何学习react
【4月更文挑战第9天】 学习React前,需掌握JavaScript基础,了解React的JSX、组件、props、state和生命周期等概念。安装Node.js和npm,用Create React App搭建环境。学习核心API,如React.createElement、React.render等,并阅读官方文档。实践项目,从Todo List开始,逐渐挑战复杂应用。同时,学习相关技术如Redux、React Router,并参与社区交流,持续关注React新发展。持之以恒,祝学习顺利!
28 10
|
3月前
|
前端开发
React查询、搜索类功能的实现
React查询、搜索类功能的实现
24 0
|
3月前
|
开发框架 前端开发 JavaScript
从零开始学习React Native开发
React Native是一种基于React框架的移动端开发框架,使用它可以快速地构建出高性能、原生的移动应用。本文将从零开始,介绍React Native的基础知识和开发流程,帮助读者快速入门React Native开发,并实现一个简单的ToDo应用程序。
|
5月前
|
人工智能 JSON 前端开发
react17+ts 学习
react17+ts 学习
|
4月前
|
前端开发
React 仿淘宝图片放大镜功能
React 仿淘宝图片放大镜功能
|
14天前
|
存储 前端开发 JavaScript
【亮剑】在React中,处理`onScroll`事件可实现复杂功能如无限滚动和视差效果
【4月更文挑战第30天】在React中,处理`onScroll`事件可实现复杂功能如无限滚动和视差效果。类组件和函数组件都能使用`onScroll`,通过`componentDidMount`和`componentWillUnmount`或`useEffect`添加和移除事件监听器。性能优化需注意节流、防抖、虚拟滚动、避免同步计算和及时移除监听器。实战案例展示了如何用Intersection Observer和`onScroll`实现无限滚动列表,当最后一项进入视口时加载更多内容。合理利用滚动事件能提升用户体验,同时要注意性能优化。
|
2月前
|
运维 JavaScript 前端开发
发现了一款宝藏学习项目,包含了Web全栈的知识体系,JS、Vue、React知识就靠它了!
发现了一款宝藏学习项目,包含了Web全栈的知识体系,JS、Vue、React知识就靠它了!
|
3月前
|
JavaScript 前端开发
在React和Vue中实现锚点定位功能
在React和Vue中实现锚点定位功能
30 1
|
3月前
|
存储 前端开发 JavaScript
从零开始学习React Native开发
【2月更文挑战第1天】React Native是一种跨平台的移动应用程序框架,可以使用JavaScript和React来构建Android和iOS应用程序。本文将带您从零开始学习React Native开发,涵盖了基础知识、组件、样式、布局、API等方面。