这个是以前刚开始写的,后来我改进了下,可以进行单元格内校验,也不用操作dom,大家可以看下最新的
直接上代码,其他项想修改也是跟Input同理
其中key值,如果连接了真实的数据,则可以绑定id(直接在Table组件上绑定rowKey)
import React, { useState, useRef } from 'react'
import { Input, Table, Button } from 'antd'
export default function Demo01() {
// input的DOM
let ipt = useRef(null)
// 失去焦点时触发
const setIptVal = (index) => {
let newData = [...data]
newData[index].name = ipt.current.input.value
setData(newData)
}
// 数据的个数
const [count, setCount] = useState(3)
// 点击增加一行
const addRow = () => {
let newData = [...data]
// 每次点击让count加1
let newCount = count
++newCount
setCount(newCount)
// 表体数据源尾部添加
newData.push({
key: count,
name: '',
age: 25,
address: 'New York No. 1 Lake Park',
})
setData(newData)
}
// 表头
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (_, record, index) => (
<Input
ref={ipt}
onBlur={() => setIptVal(index)}
defaultValue={record.name}
/>
),
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
]
// 表体数据源
const [data, setData] = useState([
{
key: '1',
name: '111',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: '222',
age: 42,
address: 'London No. 1 Lake Park',
},
])
return (
<div>
<Button onClick={addRow} type="primary">
增加一行
</Button>
<Table columns={columns} dataSource={data} />
</div>
)
}
效果如下
antDesign库的table组件里也有类似的效果(我看了几遍,没研究明白)
原文链接:https://blog.csdn.net/qq_52845451/article/details/127821860
此处评论已关闭