antd的form组件配合upload组件的使用。

在实际的业务场景中,form表单里面提交upload是一个非常普遍的应用场景。
这里记录下,自己使用form表单,upload图片的代码。
话不多说 ,直接上代码。

封装一下upload组件

import * as React from 'react';
import { Icon, Modal, Upload } from 'antd';

export default class PallWrop extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  render() {
    const { fileList, imgNumber,onChange } = this.props;
    const list = fileList||[]
    const { previewVisible, previewImage } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action="http://localhost:7001/api/upload"
          listType="picture-card"
          fileList={list}
          onChange={onChange}
          onPreview={this.handlePreview}
        >
          {list.length >= imgNumber ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

父组件

import React from 'react';
import { Form } from 'antd';
import PallWrop from './PallWrop';
const FormItem = Form.Item;
@Form.create()
export default class Test extends React.Component {
  state = {
    fileList: [
      {
        status: 'done',
        uid: 0,
        url: 'http://localhost:7001/public/images/kele.jpg',
      },
    ],
  };

  componentDidMount() {
    const { form } = this.props;
    const { fileList } = this.state;
    form.setFieldsValue({ pictures: fileList });
  }

  handleOnChange = ({ fileList }) => {
    console.log(fileList)
    return fileList.map(file => ({
      status: file.status,
      uid: file.uid,
      url: file.response?file.response.data.url:file.url,
    }));
  };

  render() {
    const {
      form: { getFieldDecorator },
      form,
    } = this.props;
    form.validateFields((error, fields) => {
      console.log(fields);
    });
    return (
      <div>
        <Form>
          <FormItem label={'商店实景图'}>
            {getFieldDecorator('pictures', {
              valuePropName: 'fileList',
              getValueFromEvent: this.handleOnChange,
            })(<PallWrop imgNumber={3} />)}
          </FormItem>
          <FormItem label={'商店实景图'}>
            {getFieldDecorator('ddd', {
              valuePropName: 'fileList',
              getValueFromEvent: this.handleOnChange,
            })(<PallWrop imgNumber={1} />)}
          </FormItem>
        </Form>
      </div>
    );
  }
}

这里说下,在formitem中,需要监听下handleOnChange ,子组件的回调,这里可以设置fileList传递的数据格式。 不太会言语,有问题可以留言~~

这里action的地址我填的是我本地的,请注意替换成对应的url

    原文作者:腹中有书气自华
    原文地址: https://segmentfault.com/a/1190000016469852
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞