antd的Table组件实现单元格可编辑
•
算法结构
目录
官网做法
其他做法
首先,官网文档上是有可编辑单元格和可编辑行的。我研究了好几遍,也是半知半解,只会用

官网做法
- 有一定的局限性,单元格内只能是输入框(我试了一些别的,不太行)
代码直接照着文档粘贴,只说一下需要改动的地方
table的数据源,我们都是后端获取,所以这里把默认的清空就行。请求接口获取数据源,直接set进去就行

然后记得给 Table 标签添加 rowKey 属性,绑定唯一值

如果想单元格可编辑,记得添加 editable: true,

下面是我自己练习的一个案例
import { Form, Input, Popconfirm, Table, Button } from 'antd'
import React, { useContext, useEffect, useRef, useState } from 'react'
import './Lll.css'
import axios from 'axios'
const EditableContext = React.createContext(null)
const EditableRow = ({ index, ...props }) => {
const [form] = Form.useForm()
return (
)
}
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false)
const inputRef = useRef(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} is required.`,
},
]}
>
) : (
{
paddingRight: 24,
}}
onClick={toggleEdit}
>
{children}
)
}
return {childNode}
}
const Lll = () => {
const [dataSource, setDataSource] = useState([])
const handleDelete = (key) => {
const newData = dataSource.filter((item) => item.key !== key)
setDataSource(newData)
}
const defaultColumns = [
{
title: '标题',
dataIndex: 'title',
width: '30%',
editable: true,
ellipsis: true,
},
{
title: '分类',
dataIndex: 'tab',
editable: true,
width: '20%',
},
{
title: '浏览量',
dataIndex: 'reply_count',
editable: true,
width: '20%',
},
{
title: 'operation',
dataIndex: 'operation',
render: (_, record) =>
dataSource.length >= 1 ? (
handleDelete(record.key)}
>
删除
) : null,
},
]
const handleSave = (row) => {
const newData = [...dataSource]
const index = newData.findIndex((item) => row.key === item.key)
const item = newData[index]
newData.splice(index, 1, {
...item,
...row,
})
setDataSource(newData)
}
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
}
const columns = defaultColumns.map((col) => {
if (!col.editable) {
return col
}
return {
...col,
onCell: (record) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
}
})
// 点击收集
const shouji = () => {
console.log('收集到的值为', dataSource)
}
// 初始化操作
useEffect(() => {
axios
.get('https://cnodejs.org/api/v1/topics')
.then((res) => {
setDataSource(res.data.data)
})
.catch((err) => console.log(err))
}, [])
return (
