场景:项目上使用到了ant design的table,需要table每列都加上开关,点击开关先弹出提示框,确认之后才可以操作
效果图:
实现过程中需要注意到的点:
1.table都很多列,避免Switch组件渲染问题,可以给组件添加key属性,key唯一
2.修改数据时,视图不会更新的问题,可能是引用类型数据导致的,可以重新换一个地址赋值。
代码如下:
import React, {useEffect, useState} from 'react';
import {Modal , Popconfirm , Switch , Table , Tooltip } from "antd";
const styles = require('./index.less');
const { confirm } = Modal;
// 配置中心
function ConfigCenter(){
const [tableData,setTableData] = useState([]);
useEffect(()=>{
const ary = [
{id:'xxas',name:'摄像头1#',status:1,delay:true,index:1},
{id:'232',name:'摄像头1#',status:1,delay:true,index:2},
{id:'adfa3',name:'摄像头1#',status:1,delay:true,index:3},
{id:'asdf4',name:'摄像头1#',status:1,delay:false,index:4},
{id:'safdz',name:'摄像头1#',status:1,delay:true,index:5},
{id:'gafgc',name:'摄像头1#',status:1,delay:false,index:6},
{id:'sdfaed',name:'摄像头1#',status:1,delay:true,index:7},
]
setTableData(ary)
},[])
const showConfirm = (id,checked)=>{
confirm({
title: `是否${checked ? '关闭' : '开启'}延时摄影?`,
content: '',
okText: '确认',
cancelText: '取消',
style:{padding:'32px 20px'},
onOk() {
onChangeSwitch(id,checked);
},
onCancel() {
console.log('Cancel');
},
});
}
// 停用单个摄像头
const handleStop = (id)=>{
console.log(id)
}
// 编辑单个摄像头
const handleEdit = (list)=>{
}
// 摄像头置顶
const handleToTop = (id)=>{
}
const onChangeSwitch = (id,checked)=>{
console.log(id,checked);
const ary = JSON.parse(JSON.stringify(tableData))
ary.forEach(item=>{
if(item.id === id){
item.delay = !item.delay;
}
})
setTableData(ary);
console.log(ary)
}
// 表格配置
const columns = [
{
title:'序号',
dataIndex:'index',
key:'index',
className: 'columnCenter',
width:100,
render:(text)=>(
{text}
)
},
{
title:'摄像头名称',
dataIndex:'name',
key:'name',
className: 'columnCenter',
width:140,
render:(text)=>(
{text}
)
},
{
title:'摄像头ID',
dataIndex:'id',
key:'id',
width:140,
className: 'columnCenter',
render:(text)=>(
{text}
)
},
{
title:'状态',
dataIndex:'status',
key:'status',
className: 'columnCenter',
width:100,
render:(text)=>(
{text===1 ? '在线' : '离线'}
)
},
{
title:'延时摄影',
dataIndex:'delay',
key:'delay',
className: 'columnCenter',
width:100,
render:(text,record)=>(
showConfirm(record.id,record.delay)}
checked={text} key={record.id}
/>
)
},
{
title:'操作',
dataIndex:'action',
key:'action',
className: 'columnCenter',
width:100,
render:(text,record)=>(
handleStop(record.id)}>
停用
handleEdit(record)}>编辑
handleToTop(record.id)}>置顶
)
},
]
return (
)
}
export default ConfigCenter;