用react hooks+typescript结合antdesign封装一个表格table组件,具体功能有增删改查,实现表格联动
时间: 2024-05-08 11:18:28 浏览: 151
好的,我了解了您的问题。下面是我给出的一些代码示例供您参考:
```tsx
import React, { useState, useEffect } from 'react';
import { Table, Modal, Form, Input, Button } from 'antd';
import { TableProps } from 'antd/lib/table';
interface EditItem {
index: number;
record: any;
}
const { confirm } = Modal;
const EditableTable: React.FC<TableProps<any>> = (props) => {
const { dataSource, columns, ...rest } = props;
const [editable, setEditable] = useState<boolean[]>(dataSource.map(() => false));
const [editItem, setEditItem] = useState<EditItem>();
const toggleEditable = (index: number) => {
setEditable((prevState) =>
prevState.map((state, i) => (i === index ? !state : state))
);
};
const handleEdit = (record: any, index: number) => {
setEditItem({ record, index });
toggleEditable(index);
};
const handleCancel = () => {
setEditItem(undefined);
setEditable((prevState) => prevState.map(() => false));
};
const handleDelete = (index: number) => {
confirm({
title: 'Do you want to delete this item?',
onOk() {
dataSource.splice(index, 1);
},
});
};
const handleOk = () => {
const form = formRef.current;
form?.validateFields((err, values) => {
if (err) {
return;
}
const newData = [...dataSource];
const { index, record } = editItem!;
newData.splice(index, 1, { ...record, ...values });
dataSource.splice(index, 1, { ...record, ...values });
setEditable((prevState) => prevState.map(() => false));
setEditItem(undefined);
});
};
const addRecord = () => {
const form = formRef.current;
form?.validateFields((err, values) => {
if (err) {
return;
}
const newData = [...dataSource];
newData.push(values);
dataSource.push(values);
});
};
const formRef = React.createRef<FormInstance>();
const EditableCell: React.FC<any> = (props) => {
const { dataIndex, title, record, index, children } = props;
const [editing, setEditing] = useState(false);
const inputRef = React.createRef<Input>();
useEffect(() => {
if (editing) {
inputRef.current?.focus();
inputRef.current?.select();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
setEditable((prevState) =>
prevState.map((state, i) => (i === index ? !state : state))
);
};
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
toggleEdit();
handleOk();
}
};
return (
<td {...props}>
{editing ? (
<Form.Item
name={dataIndex}
style={{ margin: 0 }}
rules={[
{
required: true,
message: `Please Input ${title}!`,
},
]}
>
<Input ref={inputRef} onPressEnter={handleKeyPress} onBlur={toggleEdit} />
</Form.Item>
) : (
<div style={{ cursor: 'pointer' }} onClick={toggleEdit}>
{children}
</div>
)}
</td>
);
};
const renderColumns = columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record: any, index: number) => ({
record,
index,
dataIndex: col.dataIndex,
title: col.title,
editing: editable[index],
}),
render: (text: any, record: any, index: number) => (
<EditableCell>{text}</EditableCell>
),
};
});
return (
<>
<Table
{...rest}
dataSource={dataSource}
columns={renderColumns}
pagination={false}
rowKey={(record) => record.id}
title={() => (
<Button type="primary" onClick={addRecord}>
Add record
</Button>
)}
/>
<Modal
title="Edit record"
visible={!!editItem}
onOk={handleOk}
onCancel={handleCancel}
>
<Form ref={formRef} initialValues={editItem?.record}>
{columns.map((col) => (
<Form.Item
key={col.dataIndex}
name={col.dataIndex}
label={col.title}
rules={[
{
required: true,
message: `Please Input ${col.title}!`,
},
]}
>
<Input />
</Form.Item>
))}
</Form>
</Modal>
</>
);
};
export default EditableTable;
```
这是一个使用 TypeScript、React Hooks、Ant Design 和可编辑表格的示例,在表格上可以执行增、删、改和查的操作。希望这能够为您提供帮助。
阅读全文