ttk-app-core
Version:
@ttk/recat enterprise develop framework
133 lines (120 loc) • 3.31 kB
JavaScript
import React, { useState, useEffect, useCallback } from 'react'
import { Table, Popconfirm } from 'antd'
import { useActions, useData, useCommit } from '@ttk/app-loader'
import EditableCell from "./editCell"
const EditableContext = React.createContext();
export default function Com(props) {
const commit = useCommit()
const actions = useActions(props)
const tableData = useData([props, 'tableData']).toJS()
const formData = useData([props, 'formData']).toJS()
const [editingKey, setEditingKey] = useState('')
useEffect(() => {
actions.getTableData() // 获取数据
})
const isEditing = record => record.key === editingKey;
const cancel = () => {
setEditingKey('');
};
const save = useCallback(() => {
console.log(formData, 11111)
const newData = [...tableData];
const index = newData.findIndex(item => editingKey === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, {
...item,
...formData,
});
commit([props, 'tableData'], { type: 'update', data: newData });
setEditingKey('');
} else {
newData.push(formData);
commit([props, 'tableData'], { type: 'update', data: newData });
setEditingKey('');
}
}, [formData])
const edit = useCallback((key) => {
setEditingKey(key);
commit([props, 'formData'], { type: 'update', data: tableData[key] });
}, [tableData])
let columns = [
{
title: '名称',
width: 100,
dataIndex: 'name',
key: 'name',
editable: true,
},
{
title: '年龄',
width: 100,
dataIndex: 'age',
key: 'age',
editable: true,
},
{ title: '列1', dataIndex: 'address', key: '1', editable: true, },
{
title: '操作',
key: 'operation',
width: 100,
render: (text, record) => {
const editable = isEditing(record);
return editable ? (
<span>
<EditableContext.Consumer>
{form => (
<a
onClick={() => save(form, record.key)}
style={{ marginRight: 8 }}
>
保存
</a>
)}
</EditableContext.Consumer>
<Popconfirm title="Sure to cancel?" onConfirm={() => cancel(record.key)}>
<a>取消</a>
</Popconfirm>
</span>
) : (
<a disabled={editingKey !== ''} onClick={() => edit(record.key)}>
修改
</a>
);
},
},
];
columns = columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
inputType: col.dataIndex === 'age' ? 'number' : 'text',
dataIndex: col.dataIndex,
title: col.title,
editing: isEditing(record),
}),
};
});
const components = {
body: {
cell: EditableCell,
},
};
return (
<React.Fragment>
<EditableContext.Provider value={formData}>
<Table
components={components}
bordered
dataSource={tableData}
columns={columns}
rowClassName="editable-row"
/>
</EditableContext.Provider>
</React.Fragment>
)
}