|
|
|
---
|
|
|
|
order: 23
|
|
|
|
title:
|
|
|
|
en-US: Editable Cells
|
|
|
|
zh-CN: 可编辑单元格
|
|
|
|
---
|
|
|
|
|
|
|
|
## zh-CN
|
|
|
|
|
|
|
|
带单元格编辑功能的表格。
|
|
|
|
|
|
|
|
## en-US
|
|
|
|
|
|
|
|
Table with editable cells.
|
|
|
|
|
|
|
|
```tsx
|
|
|
|
import React, { useContext, useState, useEffect, useRef } from 'react';
|
|
|
|
import { Table, Input, Button, Popconfirm, Form } from 'antd';
|
|
|
|
|
|
|
|
const EditableContext = React.createContext<any>();
|
|
|
|
|
|
|
|
interface Item {
|
|
|
|
key: string;
|
|
|
|
name: string;
|
|
|
|
age: string;
|
|
|
|
address: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface EditableRowProps {
|
|
|
|
index: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
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: string;
|
|
|
|
record: Item;
|
|
|
|
handleSave: (record: Item) => void;
|
|
|
|
}
|
|
|
|
|
|
|
|
const EditableCell: React.FC<EditableCellProps> = ({
|
|
|
|
title,
|
|
|
|
editable,
|
|
|
|
children,
|
|
|
|
dataIndex,
|
|
|
|
record,
|
|
|
|
handleSave,
|
|
|
|
...restProps
|
|
|
|
}) => {
|
|
|
|
const [editing, setEditing] = useState(false);
|
|
|
|
const inputRef = useRef();
|
|
|
|
const form = useContext(EditableContext);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (editing) {
|
|
|
|
inputRef.current.focus();
|
|
|
|
}
|
|
|
|
}, [editing]);
|
|
|
|
|
|
|
|
const toggleEdit = () => {
|
|
|
|
setEditing(!editing);
|
|
|
|
form.setFieldsValue({ [dataIndex]: record[dataIndex] });
|
|
|
|
};
|
|
|
|
|
|
|
|
const save = async e => {
|
|
|
|
try {
|
|
|
|
const values = await form.validateFields();
|
|
|
|
|
|
|
|
toggleEdit();
|
|
|
|
handleSave({ ...record, ...values });
|
|
|
|
} catch (errInfo) {
|
|
|
|
console.log('Save failed:', errInfo);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
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}>
|
|
|