用 ant-design-pro 版本v5.2.0, 写一个上传文件/图片 组件
时间: 2024-06-11 20:07:36 浏览: 164
由于 antd-pro 版本 v5.2.0 没有提供上传文件/图片组件,因此需要自己编写。以下是一个简单的上传文件/图片组件,使用 antd-pro 的 Upload 和 Modal 组件。
```javascript
import React, { useState } from 'react';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
const UploadImage = ({ value, onChange, maxCount = 1, accept = 'image/*' }) => {
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState('');
const handleCancel = () => setPreviewVisible(false);
const handlePreview = (file) => {
setPreviewImage(file.url || file.thumbUrl);
setPreviewVisible(true);
};
const handleChange = ({ fileList }) => {
onChange(fileList);
};
const uploadButton = (
<div>
<PlusOutlined />
<div style={{ marginTop: 8 }}>上传</div>
</div>
);
const fileList = value || [];
return (
<>
<Upload
accept={accept}
listType="picture-card"
fileList={fileList}
onPreview={handlePreview}
onChange={handleChange}
beforeUpload={(file) => {
if (fileList.length >= maxCount) {
message.warning(`最多只能上传 ${maxCount} 张图片`);
return false;
}
}}
>
{fileList.length >= maxCount ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
<img alt="预览" style={{ width: '100%' }} src={previewImage} />
</Modal>
</>
);
};
export default UploadImage;
```
使用示例:
```javascript
import React, { useState } from 'react';
import UploadImage from './UploadImage';
const Demo = () => {
const [images, setImages] = useState([]);
const handleChange = (fileList) => {
setImages(fileList);
};
return (
<div>
<UploadImage value={images} onChange={handleChange} maxCount={3} accept="image/*" />
</div>
);
};
export default Demo;
```
在上面的示例中,使用 UploadImage 组件来上传图片,通过 value 和 onChange 属性来控制上传的图片。maxCount 属性用于限制最多上传的图片数量,accept 属性用于限制上传的文件类型。
阅读全文