import React, { useState } from 'react';
import { Form, Input, Table, Button, Typography } from 'antd';
Copy the code
const [data, setData] = useState([]); // Store the table contents
const [form] = Form.useForm();
const [editingKey, setEditingKey] = useState(' ');
Copy the code
The page elements
<div className={styles.btn} style={{ width: '100px'}} onClick={add}> Add a new line </div><div className={styles.tableWrapper}>
<Form form={form} component={false}>
<Table
components={{
body: {
cell: EditableCell,}}}bordered
dataSource={data}
columns={mergedColumns}
rowClassName="editable-row"
pagination={false}
/>
</Form>
</div>
Copy the code
configuration
const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ... restProps }) = > {
const inputNode = <Input autoComplete="off" />;
return (
<td {. restProps} >
{editing ? (
<Form.Item
name={dataIndex}
style={{
margin: 0,}}rules={[
{
required: true.message:'Please enter ${title}! `,}},] >
{inputNode}
</Form.Item>
) : (
children
)}
</td>
);
};
Copy the code
Save, cancel and edit columns
const edit = (record) = > {
form.setFieldsValue({
personName: ' '.companyName: ' '.recommendedTime: ' '. record, }); setEditingKey(record.key); };const cancel = () = > {
setEditingKey(' ');
};
const save = async (key) => {
try {
const row = await form.validateFields();
const newData = [...data];
const index = newData.findIndex((item) = > key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, {... item, ... row }); setData(newData); setEditingKey(' ');
} else {
newData.push(row);
setData(newData);
setEditingKey(' '); }}catch (errInfo) {
console.log('Save failed', errInfo); }};Copy the code
columns
const columns = [
{
title: 'Recommended Talent'.dataIndex: 'personName'.width: '25%'.editable: true}, {title: 'Enterprises in Residence'.dataIndex: 'companyName'.width: '40%'.editable: true}, {title: 'Recommended time'.dataIndex: 'recommendedTime'.width: '15%'.editable: true}, {title: 'operation'.dataIndex: 'operation'.render: (_, record) = > {
const editable = isEditing(record);
return editable ? (
<span>
<a
onClick={()= >Save (record.key)} style={{marginRight: 8,}} > Save</a>
<a onClick={cancel}>cancel</a>
</span>
) : (
<Typography.Link disabled={editingKey! = =' '} onClick={()= >Edit (record)} > edit</Typography.Link>); }},];// Return different elements depending on whether they can be edited
const mergedColumns = 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),
}),
};
});
Copy the code
Button adds a new row
const add = () = > {
data.push({
key: "" + data.length,
personName: ' '.companyName: ' '.recommendedTime: ' ',
})
setData([...data])
}
Copy the code