zoukankan      html  css  js  c++  java
  • antd自定义upload组件在Form中使用

    直接贴代码:

    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>
          }
    }
    
  • 相关阅读:
    跳槽“六要”你懂吗?[转载]
    基于RFID 技术的仓储物流入库流程设计[转载]
    RFID:物流时代的新宠儿[转载]
    WEB界面设计五种特征[转]
    全国物流快递查询网址大全
    职员想跳槽,公司应检讨[转]
    商品条码管理办法 (2005)
    让总裁夜不成眠三件事[转]
    Google地图的配色问题(以及MapBar和51ditu)
    薪酬公开还是保密[转]
  • 原文地址:https://www.cnblogs.com/musiq66/p/13347201.html
Copyright © 2011-2022 走看看