|
| 1 | +```jsx |
| 2 | + |
| 3 | +/** |
| 4 | + * title: 纯前端表格带操作 |
| 5 | + * desc: 此例子用来解决:纯前端表格,对表格进行增删操作时,表格数据源异常的问题(利用对象的引用特性解决) |
| 6 | + */ |
| 7 | +import React, { useState, useEffect } from 'react'; |
| 8 | +import { CTable, Button } from 'cloud-react'; |
| 9 | + |
| 10 | +export default function CTableDemo() { |
| 11 | + const [data, setData] = useState([ |
| 12 | + { id: '121410327', name: '手机号优先继续发送1', createTime: '2021/12/14 10:19:02', creator: 'liyuan.meng', num: '12,222' }, |
| 13 | + { id: '121410328', name: 'ouid疲劳度3', createTime: '2021/12/13 15:47:33 ', creator: 'jiaojiao.diao', num: '198' }, |
| 14 | + { id: '121410329', name: '继续发送手机1', createTime: '2021/12/13 15:36:42', creator: 'nan.run', num: '1,232' }, |
| 15 | + { id: '121408294', name: '继续发送手机2', createTime: '2021/12/13 11:14:40', creator: 'xiaotong.fan', num: '12,122,112' }, |
| 16 | + { id: '121407191', name: '继续发送手机3', createTime: '2021/12/13 11:03:05', creator: 'zhenxiao.guo', num: '1000,000' }, |
| 17 | + ]); |
| 18 | + |
| 19 | + // (1)定义一个 buffer 对象,将 data 赋值给 buffer.bufferData,并监听 data 变化更新 buffer |
| 20 | + const [buffer] = useState({ bufferData: data }); |
| 21 | + useEffect(() => { |
| 22 | + buffer.bufferData = data; |
| 23 | + }, [data]); |
| 24 | + |
| 25 | + // (2)删除操作使用 buffer.bufferData 处理 |
| 26 | + const onDelete = row => { |
| 27 | + const targetIndex = buffer.bufferData.findIndex(item => item.id === row.id); |
| 28 | + if (targetIndex > -1) { |
| 29 | + buffer.bufferData.splice(targetIndex, 1); |
| 30 | + } |
| 31 | + setData([...buffer.bufferData]); |
| 32 | + } |
| 33 | + |
| 34 | + // (3)新增操作使用 buffer.bufferData 处理 |
| 35 | + const onAdd = () => { |
| 36 | + setData([...buffer.bufferData, { id: new Date().getTime(), name: '手机号优先继续发送1', createTime: '2021/12/14 10:19:02', creator: 'liyuan.meng', num: '12,222' }]) |
| 37 | + }; |
| 38 | + |
| 39 | + const columns = [ |
| 40 | + { title: '活动ID', dataIndex: 'id', width: 130 }, |
| 41 | + { title: '活动名称', dataIndex: 'name', width: 140 }, |
| 42 | + { title: '创建时间', dataIndex: 'createTime', width: 140 }, |
| 43 | + { title: '人数', dataIndex: 'num', align: 'right', width: 120 }, |
| 44 | + { title: '创建人', dataIndex: 'creator', width: 130 }, |
| 45 | + { |
| 46 | + title: '操作', |
| 47 | + dataIndex: 'creator', |
| 48 | + width: 100, |
| 49 | + render: (_, row) => { |
| 50 | + return ( |
| 51 | + <Button type="text" onClick={() => onDelete(row)}>删除</Button> |
| 52 | + ) |
| 53 | + } |
| 54 | + } |
| 55 | + ]; |
| 56 | + |
| 57 | + return ( |
| 58 | + <div> |
| 59 | + <Button style={{ marginBottom: 20 }} onClick={onAdd}>新增数据</Button> |
| 60 | + <CTable |
| 61 | + maxHeight={260} |
| 62 | + columnData={columns} |
| 63 | + ajaxData={{ totals: data.length, data }} |
| 64 | + /> |
| 65 | + </div> |
| 66 | + ); |
| 67 | +} |
| 68 | +``` |
0 commit comments