ant-design自定义FormItem--上传文件组件

自定义上传组件,只需要在内部的值变化之后调用props中的onChange方法就可以托管在From组件中,

此外为了保证,初始化值发生变化后组件也发生变化,需要检测initialValue 变化,这是定义了

checkInitialValue 方法,在render的时候调用
import React from 'react';
import { Upload, message, Button, Icon } from 'antd';
import { upload, search } from '@/services/upload';

class UploadFile extends React.PureComponent {
  constructor() {
    super();
    this.getfiletimeout = null;
    this.state = { fileIds: [], fileList: [] };
    this.isEmpty = true;
  }

  queryFileIds = idstr => {
    const self = this;

    if (idstr && idstr.split) {
      const ids = idstr.split(',');
      this.isEmpty = false;
      ids.forEach(id => {
        self.queryFileId(id);
      });
    } else if (!this.isEmpty) {
      this.setEmpty();
    }
  };

  queryFileId = id => {
    const { fileIds } = this.state;
    if (id && fileIds.indexOf(id) < 0) {
      // fileIds.push(id);
      this.getFile2(id);
      this.fid = id;
    }
  };

  getFile2 = id => {
    const self = this;
    search({ id: id }).then(res => {
      if (res && res.success && res.data && res.data.length > 0) {
        const ff = self.dbInfoToFileInfo(res.data[0]);
        ff.status = 'done';
        self.addFile(ff);
      }
    });
    // clearTimeout(self.getfiletimeout);
    // self.getfiletimeout = null;
  };

  addFile = file => {
    const { fileList = [], fileIds = [] } = this.state;
    if (fileIds.indexOf(file.id) < 0) {
      fileIds.push(file.id);
      const newFiles = [...fileList, file];
      // this.setState({ fileList: newFiles });
      this.updateValue(newFiles);
    }
  };

  removeFile = file => {
    const { fileList = [] } = this.state;
    const newFiles = [];
    const newIds = [];
    fileList.forEach(file1 => {
      if (file1.id !== file.id) {
        newFiles.push(file1);
        newIds.push(file1.id);
      }
    });
    this.updateValue(newFiles, newIds);
  };

  setEmpty = () => {
    this.isEmpty = true;
    // this.setState({ fileList: [], fileIds: [] });
    this.updateValue([])
  };

  updateValue = (fileList = []) => {
    const { onChange } = this.props;
    const ids = fileList.map(file => file.id);
    onChange(ids.join());
    this.setState({ fileList: fileList, fileIds: ids });
  };

  dbInfoToFileInfo = (d = {}) => {
    const f = {};
    f.name = d.fileName;
    f.uid = d.id;
    f.type = d.fileType;
    f.id = d.id;
    f.url = `/springboot/attachment/get?id=${d.id}`;
    return f;
  };

  checkInitialValue = () => {
    try {
      const v = this.props['data-__meta'].initialValue;
      if (v !== this.initialValue) {
        this.props.onChange(v);
      }
      this.initialValue = v;
    } catch (e) {
      // const msg = e;
      console.log(e);
    }
  };

  upload = ({
    file,
    filename,
    // headers,
    //  onError,
    // onProgress,
    onSuccess,
    //  withCredentials,
  }) => {
    const self = this;
    const p = {};
    p[filename] = file;

    upload(p).then(res => {
      const info = {
        file: {
          status: 'done',
        },
        fileList: [],
      };
      if (res && res.success && res.data && res.data.length > 0) {
        const ff = self.dbInfoToFileInfo(res.data[0]);
        ff.status = 'done';
        self.addFile(ff);
        info.file = ff;
        // onChange(res.data[0].id);
      } else {
        info.file.status = 'error';
      }

      onSuccess(info);
    });
  };

  render() {
    const self = this;
    const { value, maxSize = 10, text = '点击上传文件' } = this.props;
    console.log(value);
    this.checkInitialValue();
    const { fileList } = this.state;
    const upprops = {
      name: 'file',
      headers: {
        authorization: 'authorization-text',
      },
      customRequest: self.upload,
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'removed') {
          self.removeFile(info.file);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败.`);
        }
      },
    };

    this.queryFileIds(value);

    return (
      <Upload {...upprops} fileList={fileList} disabled={maxSize <= fileList.length}>
        <Button>
          <Icon type="upload" />
          {text}
        </Button>
      </Upload>
    );
  }
}

export default UploadFile;

 使用自定义上传组件

const TemplateFileIdItem = props => {
  const { data, form, style } = props;
  console.log(data.templateFileId)
  return (
    <FormItem
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 15 }}
      style={{ ...style }}
      label="模板文件"
    >
      {form.getFieldDecorator('templateFileId', {
        rules: [{ required: false, message: '请输入副标题' }],
        initialValue: data.templateFileId,
      })(<FileUpload placeholder="请输入" autoComplete="off" maxSize={1} />)}
    </FormItem>
  );
};
原文地址:https://www.cnblogs.com/Leechg/p/11162068.html