import React, { useState, useEffect, useContext, useRef } from ‘react’;
import { connect } from ‘dva’;
import {
Button,
Table,
Row,
Form,
DatePicker,
Input,
Col,
message,
Select,
} from ‘antd’;
import moment from ‘moment’;
const { Option } = Select;
const { TextArea } = Input;
const EditableContext = React.createContext(null);
const EditableRow = ({ index, …props }) => {
const [form] = Form.useForm();
return (
<EditableContext.Provider value={form}>
<tr {…props} />
</EditableContext.Provider>
);
};
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
…restProps
}) => {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
const form = useContext(EditableContext);
useEffect(() => {
if (editing) {
inputRef.current.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({
[dataIndex]: record[dataIndex],
});
};
const save = async () => {
const values = await form.validateFields();
toggleEdit();
handleSave({ …record, …values });
};
let childNode = children;
if (editable) {
childNode = editing ? (
<Form.Item
style={{
margin: 0,
}}
name={dataIndex}
rules={[
{
required: true,
message: ${title} 不能为空
,
},
]}
>
</Form.Item>
) : (
<div
className=“editable-cell-value-wrap”
style={{
paddingRight: 24,
}}
onClick={toggleEdit}
>
{children}
);
}
return <td {…restProps}>{childNode};
};
function EditInfo(props) {
const [form] = Form.useForm();
const [dataSource, setDataSource] = useState([]);
// 定义可编辑的row和cell
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
// 将修改值重新赋给dataSource。
const handleSave = (row) => {
const newData = […dataSource];
const index = newData.findIndex(item => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, { …item, …row });
setDataSource(newData);
};
const columns = [
{
title: '序号',
width: 50,
key: '1',
render: (text, record, index) => index + 1,
},
{
title: '信息编号',
dataIndex: 'infoUuid',
key: '2',
width: 200,
editable: true,
},
{
title: '信息名称',
dataIndex: 'infoName',
key: '3',
width: 300,
editable: true,
},
];
// 为columns的每一列都增加onCell属性。
const newColumns = columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
};
});
return (
<Table
components={components}
bordered
rowKey={(record, index) => `complete${record.id}${index}`}
rowClassName={setRowClassName}
columns={newColumns}
dataSource={dataSource}
pagination={false}
rowSelection={rowSelection}
/>
</div>
)
}
export default connect(({ infoTask }) => infoTask)(EditInfo);