1. 程式人生 > >antd的form元件配合upload元件的使用。

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傳遞的資料格式。 不太會言語,有問題可以留言~~