emmm之前写了两篇可编辑表格,结果使用起来还是有点小bug,在antd官方和同事的帮助下,终于get到了EditableProTable正确的使用方式,bug也都解决了。
下面的代码可以通过EditableProTable完成部门和人员的联动,也可以控制是否可编辑等。 部门选择之后,会请求接口加载该部门下的人员数据,如果修改部门的话,已经选中的人员也是要清空的。
//return里面的 可编辑表格外面没有加一层form,直接通过value和onChange赋值的。
<EditableProTable
rowKey="id"
value={dataSource}
onChange={(values) => {
setDataSource(values);
}}
editableFormRef={editorFormRef}
actionRef={actionRef}
scroll={{ x: 'calc(800px + 80%)' }}
columns={columns}
size="large"
recordCreatorProps={{
position: 'bottom',
record: (index: number) => {
return {
id: index.toString(), //id string类型,最好不要写随机数。
};
},
disabled: loadings,
//控制添加一行的那个按钮是否显示
hidden: !(flowActivityId == 'task_qlty_error_ycgs' && flowInProcess),
}}
editable={{
type: 'single',
editableKeys,
onChange: setEditableRowKeys,
onlyAddOneLineAlertMessage: '请保存后再新增!',
actionRender: (_, __, defaultDom) => {
return [defaultDom.save, defaultDom.cancel];
//只保留了保存和取消的按钮
},
}}
/>
//column里面写的部分内容,主要是责任部门和责任人的联动,选择责任人之后
{
title: '责任部门',
dataIndex: 'responsibleDeptId',
key: 'responsibleDeptId',
width: '18%',
align: 'center',
formItemProps: {
rules: [{ required: true, message: '请输入责任部门' }],
},
valueType: 'treeSelect',
valueEnum: Object.fromEntries(
[...deptName.current].map(([key, value]) => [key, { text: value }]),
),
editable: () => flowActivityId == 'task_qlty_error_ycgs' && flowInProcess,
//在fieldProps里面去写valueType中确定的组件的属性,可以获取到该行的数据。
fieldProps: (_, { rowIndex }) => {
return {
options: treeSelect,
treeExpandedKeys: expandKeys,
onTreeExpand: (expandedKeys) => {
setExpandKeys(expandedKeys);
},
onChange: (value: number) => {
//这个是完成部门人员联动的函数
selectPerson(value, rowIndex);
//这里有坑
editorFormRef.current?.setRowData?.(rowIndex, { responsibleId: undefined });
//清空之后触发表单验证
setTimeout(() => {
editorFormRef.current?.validateFields();
}, 100);
},
treeLine: true,
};
},
},
{
title: '责任人',
dataIndex: 'responsibleId',
key: 'responsibleId',
width: '12%',
valueType: 'select',
formItemProps: {
rules: [{ required: true, message: '请输入责任人' }],
},
editable: () => flowActivityId == 'task_qlty_error_ycgs' && flowInProcess,
valueEnum: () => {
return Object.fromEntries([...peopleMap].map(([key, value]) => [key, { text: value }]));
},
fieldProps: (_, { rowIndex }) => {
return {
options: peopleOptionArr[rowIndex],
};
},
align: 'center',
},
这里的坑就在于我想要清空掉责任人的数据时,用了这个setRowData函数editorFormRef.current?.setRowData?.(rowIndex, { responsibleId: undefined });
然后我id之前是用随机数设置的,根据行号去清空数据是有问题的,debug了很久。后来规范了id之后,根据行号和id去清空都可以了。之前自定义组件这样写也是可以的。