ant-design自定义FormItem--上传文件组件
2024-09-05 10:42:33
自定义上传组件,只需要在内部的值变化之后调用props中的onChange方法就可以托管在From组件中,
此外为了保证,初始化值发生变化后组件也发生变化,需要检测initialValue 变化,这是定义了
checkInitialValue 方法,在render的时候调用
import React from 'react';
import { Upload, message, Button, Icon } from 'antd';
import { upload, search } from '@/services/upload'; class UploadFile extends React.PureComponent {
constructor() {
super();
this.getfiletimeout = null;
this.state = { fileIds: [], fileList: [] };
this.isEmpty = true;
} queryFileIds = idstr => {
const self = this; if (idstr && idstr.split) {
const ids = idstr.split(',');
this.isEmpty = false;
ids.forEach(id => {
self.queryFileId(id);
});
} else if (!this.isEmpty) {
this.setEmpty();
}
}; queryFileId = id => {
const { fileIds } = this.state;
if (id && fileIds.indexOf(id) < 0) {
// fileIds.push(id);
this.getFile2(id);
this.fid = id;
}
}; getFile2 = id => {
const self = this;
search({ id: id }).then(res => {
if (res && res.success && res.data && res.data.length > 0) {
const ff = self.dbInfoToFileInfo(res.data[0]);
ff.status = 'done';
self.addFile(ff);
}
});
// clearTimeout(self.getfiletimeout);
// self.getfiletimeout = null;
}; addFile = file => {
const { fileList = [], fileIds = [] } = this.state;
if (fileIds.indexOf(file.id) < 0) {
fileIds.push(file.id);
const newFiles = [...fileList, file];
// this.setState({ fileList: newFiles });
this.updateValue(newFiles);
}
}; removeFile = file => {
const { fileList = [] } = this.state;
const newFiles = [];
const newIds = [];
fileList.forEach(file1 => {
if (file1.id !== file.id) {
newFiles.push(file1);
newIds.push(file1.id);
}
});
this.updateValue(newFiles, newIds);
}; setEmpty = () => {
this.isEmpty = true;
// this.setState({ fileList: [], fileIds: [] });
this.updateValue([])
}; updateValue = (fileList = []) => {
const { onChange } = this.props;
const ids = fileList.map(file => file.id);
onChange(ids.join());
this.setState({ fileList: fileList, fileIds: ids });
}; dbInfoToFileInfo = (d = {}) => {
const f = {};
f.name = d.fileName;
f.uid = d.id;
f.type = d.fileType;
f.id = d.id;
f.url = `/springboot/attachment/get?id=${d.id}`;
return f;
}; checkInitialValue = () => {
try {
const v = this.props['data-__meta'].initialValue;
if (v !== this.initialValue) {
this.props.onChange(v);
}
this.initialValue = v;
} catch (e) {
// const msg = e;
console.log(e);
}
}; upload = ({
file,
filename,
// headers,
// onError,
// onProgress,
onSuccess,
// withCredentials,
}) => {
const self = this;
const p = {};
p[filename] = file; upload(p).then(res => {
const info = {
file: {
status: 'done',
},
fileList: [],
};
if (res && res.success && res.data && res.data.length > 0) {
const ff = self.dbInfoToFileInfo(res.data[0]);
ff.status = 'done';
self.addFile(ff);
info.file = ff;
// onChange(res.data[0].id);
} else {
info.file.status = 'error';
} onSuccess(info);
});
}; render() {
const self = this;
const { value, maxSize = 10, text = '点击上传文件' } = this.props;
console.log(value);
this.checkInitialValue();
const { fileList } = this.state;
const upprops = {
name: 'file',
headers: {
authorization: 'authorization-text',
},
customRequest: self.upload,
onChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'removed') {
self.removeFile(info.file);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} 上传成功`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} 上传失败.`);
}
},
}; this.queryFileIds(value); return (
<Upload {...upprops} fileList={fileList} disabled={maxSize <= fileList.length}>
<Button>
<Icon type="upload" />
{text}
</Button>
</Upload>
);
}
} export default UploadFile;
使用自定义上传组件
const TemplateFileIdItem = props => {
const { data, form, style } = props;
console.log(data.templateFileId)
return (
<FormItem
labelCol={{ span: 5 }}
wrapperCol={{ span: 15 }}
style={{ ...style }}
label="模板文件"
>
{form.getFieldDecorator('templateFileId', {
rules: [{ required: false, message: '请输入副标题' }],
initialValue: data.templateFileId,
})(<FileUpload placeholder="请输入" autoComplete="off" maxSize={1} />)}
</FormItem>
);
};
最新文章
- Python批量扫描服务器指定端口状态
- C#委托与事件的简单使用
- 【瞎想】TDD与汉字;FDD与英语字母
- iOS求职之OC面试题
- Ext JS 5的声明式事件监听
- 定义文档兼容性,让IE按指定的版本解析我们的页面
- MVVM Light中的Message
- C语言链表操作模板(添加,删除,遍历,排序)
- MyBatis浅尝笔记
- 在64位Ubuntu系统上安装32位程序包
- # openVPN+LDAP AD认证,组权限管理
- python语言学习笔记整理
- 洛谷 P3177 树上染色 解题报告
- opencv学习之路(40)、人脸识别算法——EigenFace、FisherFace、LBPH
- Js2WordCloud 词云用法
- Laravel Homestead 离线安装
- web项目错误—Java.util.ConcurrentMidificationException
- 【Leetcode】【Easy】Compare Version Numbers
- springsecurity basic 认证
- ztree的用法