直接贴代码:
import React, { useState, useEffect, forwardRef } from 'react';
import { Upload, Icon, Modal, message } from 'antd';
import config from '@/config';
// 使用forwardRef是为了在Form中拿到ref
const CustomUpload = forwardRef((props, _ref) => {
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState('');
const [fileList, setFileList] = useState([]);
useEffect(() => {
setPreviewImage(props.previewImage);
setFileList(props.fileList);
}, [props]);
useEffect(() => {
if (props.fileString) {
receiveImg(props.fileString);
}
}, [props.fileString]);
const beforeUpload = file => {
return new Promise(function (resolve, reject) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片最大2M!');
reject(false);
} else {
resolve(file);
}
});
};
const receiveImg = url => {
let _fileList = [];
if (url) {
url.split(',').forEach((element, index) => {
if (element) {
_fileList.push({
url: element,
status: 'done',
uid: index,
});
}
});
setFileList(_fileList);
}
};
const handlePreview = file => {
setPreviewImage(file.url || file.thumbUrl);
setPreviewVisible(true);
};
const uploadButton = (
<div>
<Icon type='plus' />
<div className='ant-upload-text'>上传图片</div>
</div>
);
return (
<div className='clearfix'>
<Upload
action={config.imgUpload}
accept='image/*'
listType='picture-card'
beforeUpload={e => beforeUpload(e)}
withCredentials={props.withCredentials || false}
fileList={fileList}
onPreview={e => handlePreview(e)}
onChange={e => props.onChange(e)}
>
{fileList.length >= 1 ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={() => setPreviewVisible(false)}>
<img alt='logo' style={{ '100%' }} src={previewImage} />
</Modal>
</div>
);
});
export default CustomUpload;
使用时:
import CustomUpload from '@/components/CustomUpload'
...
...
class SomeComponent extends Component {
constructor(props) {
super(props)
this.state = {
...,
image: '',
imageList: [],
},
}
handleUploadChange = ({ file, fileList }) => {
this.setState({ imgList: fileList });
if (!!fileList && fileList.length && fileList[0].hasOwnProperty('response')) {
if (!!fileList[0].response && fileList[0].response.success) {
this.setState({ image: fileList[0].response.data });
}
}
};
render () {
const { image, imageList } = this.state;
...
<Form.Item label='照片' extra='请上传2MB内的图片' {...formItemLayout}>
{getFieldDecorator('image', {
getValueFromEvent: info => {
console.log(info);
return info.file && info.file.response;
},
required: true,
message: '请上传图片',
})(
<CustomUpload
fileList={imgList}
previewImage={this.props.form.getFieldValue('image')}
withCredentials={true}
onChange={this.handleUploadChange}
/>
)}
</Form.Item>
}
}