单个上传没问题,需求:一个循环中有上传的按钮点击上传图片 问题:循环出来多个上传按钮 点击一个上传 所有的都上传了
需求 每个人后后面对应的都有一个上传
代码
```xml
import React, { Component } from "react";
import { Upload, Icon, message, Modal } from 'antd';
import "./img-upload.css"
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
function beforeUpload(file) {
//限制图片 格式、size、分辨率
const isJPG = file.type === 'image/jpg';
const isJPEG = file.type === 'image/jpeg';
const isGIF = file.type === 'image/gif';
const isPNG = file.type === 'image/png';
if (!(isJPG || isJPEG || isGIF || isPNG)) {
message.error('只能上传JPG 、JPEG 、GIF、 PNG格式的图片~')
}
const isLt4M = file.size / 1024 / 1024 < 4;
if (!isLt4M) {
message.error('超过4M限制,不允许上传~')
}
return new Promise((resolve, reject) => {
if ((isJPG || isJPEG || isGIF || isPNG) && isLt4M) {
resolve()
} else {
reject()
}
});
}
export default class ImgUpload extends Component {
state = {
previewVisible: false,
previewImage: '',
fileLists:[
{fileList: this.props.fileList || [],}
]
,
lock: false
};
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.fileList !== prevState.fileList) {
return ({ fileList: nextProps.fileList })
}
return null
}
handleCancel = () => this.setState({ previewVisible: false });
handlePreview = async file => {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
// console.log
this.setState({
previewImage: file.url || file.preview,
previewVisible: true,
});
};
handleChange = ({ fileList }) => {
// console.log('####', fileList)
console.log(fileList)
this.setState({ fileList })
// this.props.content
this.props.onChange(fileList)
};
render() {
const { previewVisible, previewImage, fileList } = this.state;
const uploadButton = (
<div>
{/* <Icon type="plus" /> */}
<div className="ant-upload-text" >Upload{this.props.content}</div>
</div>
);
return (
<div className="clearfix">
<Upload
listType="picture-card"
fileList={fileList}
onPreview={this.handlePreview}
beforeUpload={beforeUpload}
onChange={this.handleChange}
>
{fileList.length >= 1 ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
);
}
}
```