#yyds干货盘点# react笔记之学习之完成删除功能
哈客cc lv.2
发布时间:2023-05-16 14:49:13 218相关标签: # 前端# less# webkit# 数据# 信息
前言
我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷
代码案例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);
文章来源: https://blog.51cto.com/u_14476028/5971579
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报