import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react' import { Form, Input, Select, Table, } from 'antd' import type { FormInstance, FormItemProps } from 'antd/es/form' import type { InputProps } from 'antd/es/input' import type { SelectProps } from 'antd/es/select' import type { ColumnType as AntdColumnType, TablePaginationConfig, TableProps as AntdTableProps, } from 'antd/es/table' // 🚧-①: 屏蔽 React.StrictMode 副作用 export interface TableProps> extends Omit, 'columns'> { columns?: (AntdColumnType & { formItem?: FormItemProps & { input?: InputProps select?: SelectProps // render props(小) render?: (...args: Parameters['render']>) => JSX.Element } })[] query?: (args: { /** 请求次数,当不想自动发起首次请求时可以判断 count==1 返回 undefined 打断请求 - 内部维护 */ count: number /** 与后端交互只需 `current` `pageSize` `total` 三个属性即可 */ pagination?: Partial> /** 来自 handle.query 透传 */ payload?: any }) => Promise<({ data: RecordType[] } & Partial>) | void> handle?: { query: (args?: Omit>[0], 'count'>) => void // React 单项数据流设计,遂抛出 dataSource data: RecordType[] // forms: FormInstance[] // TODO: FormInstance } } export type TableColumn> = TableProps['columns'][number] export type TableQuery> = TableProps['query'] export type TableHandle> = TableProps['handle'] // Table 的可编辑表格的表单组件样式(对齐单元格) function formatStyle() { const id = 'tr-form-item_style' const className = 'tr-form-item' let oStyle = document.getElementById(id) as HTMLStyleElement if (oStyle) return oStyle = document.createElement<'style'>('style') oStyle.id = id oStyle.innerHTML = `.${className} .ant-form-item { margin: 0; }` document.head.appendChild(oStyle) } function TableAntd, FormValues = Record>(props: TableProps) { const { columns, dataSource, handle, query, onChange, pagination: props_pagination, ...rest } = props const [data, setData] = useState(dataSource) const [page, setPage] = useState(props_pagination === false ? false : { showQuickJumper: true, ...props_pagination, }) const [loading, setLoading] = useState(false) const queryCount = useRef(0) const queryArgs = useRef[0]>() // query's args cache const mounted = useRef(false) const unMounted = useRef(false) const editable = useMemo(() => columns.find(col => col.formItem), [columns]) useLayoutEffect(() => { unMounted.current = false // 🚧-① formatStyle() }, []) // 请求 const queryHandle = async (args: Parameters[0] = {}) => { if (!query) return queryCount.current++ const pagination = args.pagination ?? (typeof page === 'object' ? { current: page.current, pageSize: page.pageSize, total: page.total, } : undefined) setLoading(true) const result = await query({ count: queryCount.current, pagination, payload: args.payload, }) setLoading(false) if (!result) return // 打断请求 or 无效请求 if (unMounted.current) return // 🚧-① const { data, ...restPage } = result setData(data) if (typeof page === 'object') { setPage({ ...page, ...restPage }) } } // 外部传入 dataSource useEffect(() => { // initialized in `useState(dataSource)` mounted.current && setData(dataSource) }, [dataSource]) // handle 挂载 useEffect(() => { if (handle) { handle.query = args => { queryArgs.current = args queryHandle(args) } handle.data = data as RecordType[] } }, [handle, data]) // init useEffect(() => { queryHandle() }, []) // componentDidMount useEffect(() => { mounted.current = true return () => { // 🚧-① queryCount.current = 0 mounted.current = false unMounted.current = true } }, []) const tableProps: AntdTableProps = { size: 'small', columns: editComponents.withOnCell(columns), dataSource: data, onChange(pagination, filters, sorter, extra) { onChange?.(pagination, filters, sorter, extra) // works without `props.query` // !query && setPage(pagination) const { current, pageSize, total } = pagination queryHandle({ pagination: { current, pageSize, total }, // use last cache payload: queryArgs.current?.payload, }) }, pagination: page, ...rest, } return ( ) } export default TableAntd // ----------------------------------------------------------------------------- // 🚧-②: 暂时屏蔽报错 // Warning: Cannot update a component (`InternalFormItem`) while rendering a different component (`Unknown`). /** * 可编辑表格实现 * @see https://ant.design/components/table/#components-table-demo-edit-cell */ function editComponents, FormValues = Record>( args: { onFieldChange?: (args: { key: string; value: any; index: number }) => void, } = {}, ): AntdTableProps['components'] { // 每行独立一个 FormInstance const EditableContext = React.createContext({} as FormInstance) return { body: { row: props => { // TODO: 考虑支持外部传入 FormInstance 达到完全可控 const [form] = Form.useForm() const { className, ...rest } = props return (
) }, cell: ({ column, record, index, children, ...restProps }) => { let childNode = children // title 列无 record if (record) { const form = useContext>(EditableContext) const { dataIndex, formItem } = (column || {}) as TableColumn const key = dataIndex as string // 初始化数据同步到 Form 中 - 回填数据 // 在 Antd 提供的 Demo 中点击可编辑 cell 时触发 form.setFieldsValue 规避频繁触发 form.setFieldsValue({ [key]: record[key] } as any) if (formItem) { const { input, select, render, } = formItem as TableColumn['formItem'] // 当前列为 Form 元素,将原数据备份到 dataIndex_old 中 const backupKey = key + '_old' if (record[backupKey] === undefined) { record[backupKey] = record[key] } if (render) { childNode = ( {render(record[key], record, index)} ) } else if (input) { const { onChange, onBlur, ...restInput } = input childNode = ( { onChange?.(event) record[key] /* 软更新 🚧-② */ = (event.target as any).value }} onBlur={event => { onBlur?.(event) args.onFieldChange?.({ key, value: event.target.value, index }) }} // 硬更新 {...restInput} /> ) } else if (select) { const { onChange, ...restSelect } = select childNode = ( }, }, } } editComponents.withOnCell = function onCell>(columns: TableColumn[]): typeof columns { return columns.map(column => ({ ...column, // 透传至 components.body.cell onCell: (record, index) => ({ column, record, index, } as any), })) }
{childNode}