做了个antd的上传简单封装,很烦。主要用的方法就是使用customRequest 这个覆盖上传组件的默认上传,实现自定义上传。有的地方可能比较low 因为我不知道其他方法。。
import React from 'react'
import {Icon,Upload,Modal} from 'antd'
import { uploadimg } from '../../api/login'
export default class UploadIcon extends React.Component{
constructor(props) {
super(props)
const value = props.value || {};
this.state = {
previewImage: '',
fileList: value|[],
max:value.max|1
}
}
customRequest = (option) => {
const that = this
const formData = new FormData();
formData.append('photo', option.file);
uploadimg(formData).then(res => {
that.state.fileList.push({
name: 'yyy.png',
status: 'done',
url: res.data[0].file_url,
})
that.state.fileList.map((v, i) => {
v.uid = i
})
that.setState({
fileList: that.state.fileList
})
that.props.onChange(that.state.fileList)
})
}
render(){
const {fileList,previewVisible,previewImage,max} = this.state
const uploadButton = (
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<div>
<Upload
action=""
listType="picture-card"
customRequest={this.customRequest}
fileList={fileList}
onPreview={this.handlePreview}
onChange={this.handleChange}
>
{fileList.length >= max ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
)
}
}
下面的是antd 上传与form结合使用的方法,这个我在网上找了好久都没找到。。。。。
在form里写这个。然后因为他这个检测是用的方法来检测
<Form.Item
label="应用图标"
>
{getFieldDecorator('icon', {
initialValue: { iconList:[] },
rules: [{ required: true,validator: this.checkImg }],
})(
<UploadIcon/> // 组件引入
)}
</Form.Item>
添加方法: callback就是返回的错误值。
checkImg = (rule, value, callback) => {
console.log(value)
if (value.length) {
callback();
return;
}
callback('请添加游戏图片');
}