ant-design/components/table/demo/edit-cell.md

276 lines
5.8 KiB
Markdown
Raw Normal View History

2016-11-21 11:29:55 +08:00
---
order: 23
2016-11-21 11:29:55 +08:00
title:
en-US: Editable Cells
zh-CN: 可编辑单元格
---
## zh-CN
带单元格编辑功能的表格。
## en-US
Table with editable cells.
```tsx
2020-01-22 12:11:49 +08:00
import React, { useContext, useState, useEffect, useRef } from 'react';
2019-05-07 14:57:32 +08:00
import { Table, Input, Button, Popconfirm, Form } from 'antd';
import { FormInstance } from 'antd/lib/form';
2018-07-10 21:10:48 +08:00
const EditableContext = React.createContext<FormInstance<any> | null>(null);
2018-07-10 21:10:48 +08:00
interface Item {
key: string;
name: string;
age: string;
address: string;
}
2018-07-10 21:10:48 +08:00
interface EditableRowProps {
index: number;
}
2016-11-21 11:29:55 +08:00
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
<Form form={form} component={false}>
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
</Form>
);
};
interface EditableCellProps {
title: React.ReactNode;
editable: boolean;
children: React.ReactNode;
dataIndex: keyof Item;
record: Item;
handleSave: (record: Item) => void;
}
2018-07-10 21:10:48 +08:00
const EditableCell: React.FC<EditableCellProps> = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
2020-01-22 12:11:49 +08:00
const [editing, setEditing] = useState(false);
const inputRef = useRef<Input>(null);
const form = useContext(EditableContext)!;
2020-01-22 12:11:49 +08:00
useEffect(() => {
if (editing) {
inputRef.current!.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({ [dataIndex]: record[dataIndex] });
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
const save = async () => {
try {
const values = await form.validateFields();
toggleEdit();
2018-07-10 21:10:48 +08:00
handleSave({ ...record, ...values });
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
let childNode = children;
if (editable) {
childNode = editing ? (
<Form.Item
style={{ margin: 0 }}
name={dataIndex}
rules={[
{
required: true,
message: `${title} is required.`,
},
]}
>
<Input ref={inputRef} onPressEnter={save} onBlur={save} />
</Form.Item>
) : (
<div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
{children}
</div>
);
2016-11-21 11:29:55 +08:00
}
return <td {...restProps}>{childNode}</td>;
};
2016-11-21 11:29:55 +08:00
type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
key: React.Key;
name: string;
age: string;
address: string;
}
interface EditableTableState {
dataSource: DataType[];
count: number;
}
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
class EditableTable extends React.Component<EditableTableProps, EditableTableState> {
columns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];
constructor(props: EditableTableProps) {
2016-11-21 11:29:55 +08:00
super(props);
2019-05-07 14:57:32 +08:00
this.columns = [
{
title: 'name',
dataIndex: 'name',
width: '30%',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
},
{
title: 'address',
dataIndex: 'address',
},
{
title: 'operation',
dataIndex: 'operation',
render: (_, record: { key: React.Key }) =>
2019-05-07 14:57:32 +08:00
this.state.dataSource.length >= 1 ? (
2018-11-28 15:00:03 +08:00
<Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
<a>Delete</a>
2018-11-28 15:00:03 +08:00
</Popconfirm>
2019-05-07 14:57:32 +08:00
) : null,
},
];
2016-11-21 11:29:55 +08:00
this.state = {
2019-05-07 14:57:32 +08:00
dataSource: [
{
key: '0',
name: 'Edward King 0',
age: '32',
address: 'London, Park Lane no. 0',
},
{
key: '1',
name: 'Edward King 1',
age: '32',
address: 'London, Park Lane no. 1',
},
],
2016-11-21 11:29:55 +08:00
count: 2,
};
}
2018-06-27 15:55:04 +08:00
handleDelete = (key: React.Key) => {
2017-02-08 14:42:17 +08:00
const dataSource = [...this.state.dataSource];
2017-08-25 16:37:00 +08:00
this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
2016-11-21 11:29:55 +08:00
handleAdd = () => {
const { count, dataSource } = this.state;
const newData: DataType = {
2016-11-21 11:29:55 +08:00
key: count,
name: `Edward King ${count}`,
age: '32',
2016-11-21 11:29:55 +08:00
address: `London, Park Lane no. ${count}`,
};
this.setState({
dataSource: [...dataSource, newData],
count: count + 1,
});
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
handleSave = (row: DataType) => {
2018-07-10 21:10:48 +08:00
const newData = [...this.state.dataSource];
const index = newData.findIndex(item => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, {
...item,
...row,
});
this.setState({ dataSource: newData });
2019-05-07 14:57:32 +08:00
};
2018-07-10 21:10:48 +08:00
2016-11-21 11:29:55 +08:00
render() {
const { dataSource } = this.state;
2018-07-10 21:10:48 +08:00
const components = {
body: {
row: EditableRow,
2018-07-10 21:10:48 +08:00
cell: EditableCell,
},
};
2019-05-07 14:57:32 +08:00
const columns = this.columns.map(col => {
2018-07-10 21:10:48 +08:00
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record: DataType) => ({
2018-07-10 21:10:48 +08:00
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave: this.handleSave,
}),
};
});
2017-02-23 11:45:48 +08:00
return (
<div>
<Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
Add a row
</Button>
2018-07-10 21:10:48 +08:00
<Table
components={components}
rowClassName={() => 'editable-row'}
bordered
dataSource={dataSource}
columns={columns as ColumnTypes}
2018-07-10 21:10:48 +08:00
/>
2017-02-23 11:45:48 +08:00
</div>
);
2016-11-21 11:29:55 +08:00
}
}
ReactDOM.render(<EditableTable />, mountNode);
2019-05-07 14:57:32 +08:00
```
2016-11-21 11:29:55 +08:00
2019-05-07 14:57:32 +08:00
```css
2016-11-21 11:29:55 +08:00
.editable-cell {
position: relative;
}
2018-07-10 21:10:48 +08:00
.editable-cell-value-wrap {
padding: 5px 12px;
2016-11-21 11:29:55 +08:00
cursor: pointer;
}
2018-07-10 21:10:48 +08:00
.editable-row:hover .editable-cell-value-wrap {
padding: 4px 11px;
2018-07-10 21:10:48 +08:00
border: 1px solid #d9d9d9;
border-radius: 4px;
2016-11-21 11:29:55 +08:00
}
2019-12-25 15:59:16 +08:00
[data-theme='dark'] .editable-row:hover .editable-cell-value-wrap {
border: 1px solid #434343;
}
2019-05-07 14:57:32 +08:00
```