前言
大家好 我是歌谣 今天要说的是ant design实现表格行编辑的功能 考虑问题的时候我们需要多看官方的api
开发开始
紧接着我们对照着api进行开发 首先加一个table
<Table onChange={onTableChange} rowKey="id" components={components} rowClassName={() => 'editable-row'} bordered dataSource={menuData.list} pagination={{ pageSizeOptions: ['5', '10', '20', '50'], total: menuData?.page.dataTotal, showTotal: () => { return '共 ' + menuData?.page.dataTotal + ' 条记录'; }, }} columns={columns as ColumnTypes} rowSelection={rowSelection} />
对component进行定义
const components = { body: { row: EditableRow, cell: EditableCell, }, };
对 EditableRow进行定义
参照官网api引入对应的依赖
const EditableContext = React.createContext<FormInstance<any> | null>(null); 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> ); };
对EditableCell进行定义
const EditableCell: React.FC<EditableCellProps> = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => { const [editing, setEditing] = useState(false); const inputRef = useRef<InputRef>(null); const form = useContext(EditableContext)!; useEffect(() => { if (editing) { inputRef.current!.focus(); } }, [editing]); const toggleEdit = () => { setEditing(!editing); form.setFieldsValue({ [dataIndex]: record[dataIndex] }); }; const save = async () => { 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}不能为空`, }, ]} > <Input ref={inputRef} onPressEnter={save} onBlur={save} /> </Form.Item> ) : ( <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}> {children} </div> ); } return <td {...restProps}>{childNode}</td>; };
handleSave进行定义
const handleSave = (row: any) => { // console.log(batchUpdateSizeList) batchUpdateSizeList([{ id: row.id, size: row.sizeName }]) .unwrap() .then((response: any) => { if (response.code === 200) { message.success("操作成功") } }); const newData: any = [...menuData.list]; const index = newData.findIndex((item: any) => row?.id == item.id); const item = newData[index]; newData.splice(index, 1, { ...item, ...row, }); setMenuData({ list: newData, page: { dataTotal: menuData.page.dataTotal, size: menuData.page.size, } }); };
handleSave中的数据是核心 利用当前行数据的回调可以处理数据和接口 完成当前行的更新
对表头column的设置
const columns = defaultColumns.map(col => { if (!col.editable) { return col; } return { ...col, onCell: (record: any) => ({ record, editable: col.editable, dataIndex: col.dataIndex, title: col.title, handleSave, }), }; });