选取的的是:表格 Table - Ant Design
其实ant design本身就有增加和删除单列数据的封装好的表格,但是个人觉得那个功能繁多,自己实现封装也便于之后理解和二次使用。
初步效果(舍去切换样式的功能):
突破的关键点就是在点击表格的每一行都是有对应的rowkey:
以此我们新增加入一行数据和删减选中数据的功能
①将表格利用useState实现响应式:
const [data,setData] = useState([
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
]);
②添加增加和删减按钮:
③新增实现代码:
新增代码
let [count,setCount]=useState(2)//每一行都有独立的的key
const adddata=()=>{
const newrowdata={
key:count,
name: 'newname',
age: 42,
address: 'newaddress',
}
//利用扩展运算符将新增数据拷贝到原数据实现新增
setData([...data,newrowdata])
setCount(count+1)
}
实现新增功能:
④删除选中行实现代码:
我们需要利用已经定义好的rowSelection收集选中行的key
let [selecteddatarowkeys,setSelecteddatarowkeys]=useState([])
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
setSelecteddatarowkeys(selectedRowKeys)
},
getCheckboxProps: (record) => ({
//设置禁用行,我们默认为第一行
disabled: record.key === '1',
}),
};
console.log('收集的选中行:'+selecteddatarowkeys)
那么就可以实现功能就很方便了:
const deletedata=()=>{
//去除data当中包含选中行的rowkeys
const newdate=data.filter(item=>!selecteddatarowkeys.includes(item.key))
setData(newdate)
}
⑤附上全部代码:
javascript">import React, { useState } from 'react';
import { Table ,Button} from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
const App = () => {//就是相当于每列的索引const columns = [{title: 'Name',dataIndex: 'name',render: (text) => <a>{text}</a>,},{title: 'Age',dataIndex: 'age',},{title: 'Address',dataIndex: 'address',},];//每列的数据const [data,setData] = useState([{key: '1',name: 'John Brown',age: 32,address: 'New York No. 1 Lake Park',},]);let [selecteddatarowkeys,setSelecteddatarowkeys]=useState([])const rowSelection = {onChange: (selectedRowKeys, selectedRows) => {console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);setSelecteddatarowkeys(selectedRowKeys)},getCheckboxProps: (record) => ({//设置禁用行,我们默认为第一行disabled: record.key === '1',}),};console.log('收集的选中行:'+selecteddatarowkeys)let [count,setCount]=useState(2)const adddata=()=>{const newrowdata={key:count,name: 'newname',age: 42,address: 'newaddress',}//利用扩展运算符将新增数据拷贝到原数据实现新增setData([...data,newrowdata])setCount(count+1)}const deletedata=()=>{//去除data当中包含选中行的rowkeysconst newdate=data.filter(item=>!selecteddatarowkeys.includes(item.key))setData(newdate)}return (<div style={{ display: 'flex' ,flexDirection:'column'}}><div className="operatedata" style={{margin:'20px'}}><Button type="primary" icon={<PlusOutlined />} onClick={adddata} style={{margin:'0 10px'}}>新增</Button><Button type="primary" icon={<MinusOutlined />} onClick={deletedata}>删减</Button></div><TablerowSelection={{...rowSelection,}}columns={columns}dataSource={data}/></div>);
};
export default App;