Улучшение редактируемой таблицы.

раздельные методы на добавление, удаление, редактирование.
This commit is contained in:
Фролов 2021-08-02 11:09:55 +05:00
parent 5d18d73d28
commit 618edda299
2 changed files with 92 additions and 35 deletions

View File

@ -1,6 +1,9 @@
import { Form, Input, Popconfirm, Typography, Table } from "antd" import { Form, Input, Table, Button, Popconfirm } from "antd"
import { EditOutlined, SaveOutlined, PlusOutlined, CloseCircleOutlined, DeleteOutlined } from '@ant-design/icons'
import { useState } from "react"; import { useState } from "react";
const newRowKeyValue = 'newRow'
const EditableCell = ({ const EditableCell = ({
editing, editing,
record, record,
@ -32,8 +35,17 @@ const EditableCell = ({
</td>) </td>)
} }
export const EditableTable = ({columns, dataSource, onUpdateData: onChange, ...otherTableProps}) => { export const EditableTable = ({
columns,
dataSource,
onChange, // Метод вызывается со всем dataSource с измененными элементами после любого действия
onRowAdd, // Метод вызывается с новой добавленной записью. Если метод не поределен, то кнопка добавления строки не показывается
onRowEdit,// Метод вызывается с новой отредактированной записью. Если метод не поределен, то кнопка редактирования строки не показывается
onRowDelete,// Метод вызывается с удаленной записью. Если метод не поределен, то кнопка удаления строки не показывается
...otherTableProps}) => {
const [form] = Form.useForm() const [form] = Form.useForm()
const [data, setData] = useState(dataSource?? [])
const [editingKey, setEditingKey] = useState('') const [editingKey, setEditingKey] = useState('')
const isEditing = (record) => record.key === editingKey const isEditing = (record) => record.key === editingKey
@ -44,57 +56,94 @@ export const EditableTable = ({columns, dataSource, onUpdateData: onChange, ...o
} }
const cancel = () => { const cancel = () => {
if(editingKey == newRowKeyValue)
{
const newData = [...data]
const index = newData.findIndex((item) => newRowKeyValue === item.key)
newData.splice(index, 1)
setData(newData)
}
setEditingKey('') setEditingKey('')
} }
const save = async (key) => { const addNewRow = () => {
let newRow = {
key:newRowKeyValue
}
const newData = [...data, newRow]
setData(newData)
edit(newRow)
}
const save = async (record) => {
try { try {
const row = await form.validateFields() const row = await form.validateFields()
const newData = [...dataSource] const newData = [...data]
const index = newData.findIndex((item) => key === item.key) const index = newData.findIndex((item) => record.key === item.key)
let item = newData[index]
if (index > -1) { newData.splice(index, 1, { ...item, ...row })
const item = newData[index]
newData.splice(index, 1, { ...item, ...row })
} else {
newData.push(row)
}
if(item.key === newRowKeyValue)
item.key = newRowKeyValue + newData.length
setEditingKey('') setEditingKey('')
setData(newData)
if (editingKey === newRowKeyValue)
onRowAdd(item)
else
onRowEdit(item)
if(onChange) if(onChange)
onChange(newData) onChange(newData)
else
console.error(`EditableTable.onChange doesn't connected`)
} catch (errInfo) { } catch (errInfo) {
console.log('Validate Failed:', errInfo) console.log('Validate Failed:', errInfo)
} }
} }
const deleteRow = (record) =>{
const newData = [...data]
const index = newData.findIndex((item) => record.key === item.key)
newData.splice(index, 1)
setData(newData)
onRowDelete(record)
if(onChange)
onChange(newData)
}
const operationColumn = { const operationColumn = {
title: '', title: (!!onRowAdd) && <Button
onClick={addNewRow}
disabled={editingKey !== ''}
icon={<PlusOutlined/>}
/>,
dataIndex: 'operation', dataIndex: 'operation',
render: (_, record) => { render: (_, record) => {
const editable = isEditing(record) const editable = isEditing(record)
return editable ? ( return editable
<span> ?(<span>
<a <Button
href="javascript:" onClick={() => save(record)}
onClick={() => save(record.key)} icon={<SaveOutlined/>}/>
style={{ <Button
marginRight: 8, onClick={cancel}
}} icon={<CloseCircleOutlined/>}/>
> </span>)
Save :(<span>
</a> <Button
<Popconfirm title="Sure to cancel?" onConfirm={cancel}> disabled={editingKey !== ''}
<a>Cancel</a> onClick={() => edit(record)}
</Popconfirm> icon={<EditOutlined/>}/>
</span> {onRowDelete&&
) : ( <Popconfirm title="Удалить?" onConfirm={()=>deleteRow(record)}>
<Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}> <Button icon={<DeleteOutlined/>}/>
Edit </Popconfirm>}
</Typography.Link> </span>)
)
}, },
} }
@ -132,7 +181,7 @@ export const EditableTable = ({columns, dataSource, onUpdateData: onChange, ...o
}, },
}} }}
columns={mergedColumns} columns={mergedColumns}
dataSource={dataSource} dataSource={data}
{...otherTableProps} {...otherTableProps}
/> />
</Form> </Form>

View File

@ -59,6 +59,10 @@ export default function WellStat({idWell}){
update(); update();
} ,[idWell]) } ,[idWell])
const onChange = (newData) =>{
setData(newData)
}
return( return(
<LoaderPortal show={showLoader}> <LoaderPortal show={showLoader}>
<EditableTable <EditableTable
@ -67,6 +71,10 @@ export default function WellStat({idWell}){
size={'small'} size={'small'}
bordered bordered
pagination={false} pagination={false}
onChange={onChange}
onRowAdd={()=>{}}
onRowEdit={()=>{}}
onRowDelete={()=>{}}
/> />
</LoaderPortal>) </LoaderPortal>)
} }