preface
Because the project needs an editable table, but the editable table provided in Antd is too cumbersome and unfriendly to use, so I wrote a simple editable table component.
The first step
First, create an EditTable.tsx file in your project; Introduce the required modules into the file;
PS: I use React Hook + TypeScript for development;
import React, { useState, useEffect } from 'react'; import { Table, Form, message, Input } from 'antd'; Import {FormComponentProps} from 'antd/lib/form'; import { ColumnProps } from 'antd/lib/table'; import { dataItemType } from './interface'; */ Interface EditTableProps extends FormComponentProps {dataSource: dataItemType[]; loading: boolean; }Copy the code
The second step
Write a component
const EditTable: React.FC<EditTableProps> = ({loading, dataSource, form: {getFieldDecorator}}) => { const [editData, setEditData] = useState<dataItemType[]>(); Const [data, setData] = useState<dataItemType>(); const [data, setData] = useState<dataItemType>(); UseEffect = () => {useEffect = () => {useEffect = () => { setEditData([...dataSource]); []}; /** * const columns: Array<ColumnProps<dataItemType>> = [{title: 'data ', dataIndex: / *... * / 'record'}, {title: 'editing', dataIndex: 'edit', render: (text: any record: any, index: number) => { return ( <Form> {getFieldDecorator(`countNum[${index}]`, { rules: [ { required: true, message: 'edit field cannot be empty,},]}) (< Input onChange = {e = > {textChange (e, record);}} / >)} < / Form >);}, ] return ( <Table columns={columns} dataSource={data} pagination={false} loading={loading} rowKey='id' /> ) } export default Form.create<EditTableProps>()(EditTable)Copy the code
The third step
Process edited data
const textChange = (e: any, record: any) => { let rows = [...data]; let row = rows.find(item => item.id === record.id); if (row) { row.countNum = e.target.value; } // Save the edited data setEditCacheData(rows); };Copy the code
At this point, a simple edit table component was wrapped up, and there might have been a better way to implement it, but this was the only way to do it because of the project event crunch.