通过react hooks 结合antd的table实现整个表格新增编辑。
引入组件依赖
import React, { useState } from 'react';
import { Table, InputNumber, Button, Space, Input } from 'antd';
定义数据
const originData = [
{ key: 1, name: '白银会员', value: 0, equity: 0, reward: 0 },
{ key: 2, name: '黄金会员', value: 500, equity: 2, reward: 1 },
{ key: 3, name: '钻石会员', value: 1000, equity: 4, reward: 1 },
{ key: 4, name: '至尊会员', value: 1500, equity: 1, reward: 0 },
];
编辑表格时触发(函数体外)
const EditableCell = ({
dataIndex,
rowIndex,
title,
record,
index,
children,
isEdit,
data,
handChange,
...restProps
}) => {
return (
<td {...restProps}>
{
isEdit ? (
// 这里可以自定义需要的类型进行处理
<Input defaultValue={data[rowIndex][dataIndex]} onChange={(e) => handChange(e.target.value, rowIndex, dataIndex)} />
) : (
children
)
}
</td>
);
};
定义函数体
export default function GradeSet() {
//旧数据
const [data, setdata] = useState(originData);
//是否编辑
const [isEdit, setisEdit] = useState(false);
//新数据
const [temData, settemData] = useState(originData);
const columns = [
{
title: '等级名称',
dataIndex: 'name',
editable: true,
},
{
title: '升级条件',
dataIndex: 'value',
editable: true,
},
{
title: '等级权益',
dataIndex: 'equity',
editable: true,
},
{
title: '升级奖励',
dataIndex: 'reward',
editable: true,
},
]
const mergedColumns = columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record, rowIndex) => ({
record,
rowIndex,
dataIndex: col.dataIndex,
title: col.title,
isEdit: isEdit,
data: temData,
handChange
}),
};
});
//取消
const handleCancel = () => {
settemData(data)
setisEdit(false)
}
//保存
const handleSave = () => {
setdata(temData);
setisEdit(false);
}
//改变时
const handChange = (value, rowIndex, dataIndex) => {
const otherData = JSON.parse(JSON.stringify(temData));
otherData[rowIndex][dataIndex] = value;
settemData(otherData)
}
// 添加
const handleAdd = () => {
const newData = [...temData];
newData.push({ key: temData.length + 1, name: `${temData.length + 1} 会员`, value: 0, equity: 0, reward: 0 },)
console.log(newData)
settemData(newData);
}
// 删除
const handleDelete = () => {
const newData = [...temData];
newData.pop();
settemData(newData);
}
return (
<div>
<div className={`headTitle`}>
<p>数据列表</p>
{
isEdit ?
<Space>
<Button onClick={() => handleCancel()}>取消</Button>
<Button type="primary" onClick={() => handleSave()}>保存</Button>
</Space>
:
<Button onClick={() => setisEdit(true)}>编辑</Button>
}
</div>
<Table
components={{ body: { cell: EditableCell } }}
bordered
dataSource={temData}
columns={mergedColumns}
rowClassName="editable-row"
pagination={false}
/>
{
isEdit ?
<Space className={s.bottom}>
<Button type="primary" onClick={() => handleAdd()}>添加等级</Button>
<Button danger onClick={() => handleDelete()}>删除最高等级</Button>
<p>修改等级获得条件的成长值后,部分客户会因无法达到该成长值要求而发生会员等级的变化</p>
</Space>
:
null
}
</div>
);
}
样式
.headTitle {
padding: 0 16px;
display: flex;
justify-content: space-between;
align-items: center;
color: #666;
height: 50px;
line-height: 50px;
background: #f0f0f0;
}