简体   繁体   English

在蚂蚁设计表单中使用`getValueFromEvent`

[英]use `getValueFromEvent` in ant design Form

i wanted to know how to use ant image picker (or any other component) in ant design form.我想知道如何在 ant 设计形式中使用 ant 图像选择器(或任何其他组件)。 and if possible i wanted to know how getValueFromEvent will be called and how to change it to make in work.如果可能的话,我想知道如何调用 getValueFromEvent 以及如何更改它以使其正常工作。

here is my sample.这是我的样本。 i think its pretty straight:我认为它很直接:

https://codesandbox.io/s/antd-reproduction-template-forked-lfk7k?file=/index.js https://codesandbox.io/s/antd-reproduction-template-forked-lfk7k?file=/index.js

this section should be trigged in some way.这部分应该以某种方式触发。

const normFile = (e) => {
  console.log("Upload event:", e);
  if (Array.isArray(e)) {
    return e;
  }
  return e && e.fileList;
};

the only thing i'm not understanding is how the event will be trigged?我唯一不明白的是事件将如何触发? i'll be thankful for any document or link or ...我会感谢任何文件或链接或...

In your code you use 'customRequest' documented as such: "Override for the default xhr behavior allowing for additional customization and ability to implement your own XMLHttpRequest"在您的代码中,您使用“customRequest”记录如下:“覆盖默认的 xhr 行为,允许额外的自定义和实现您自己的 XMLHttpRequest 的能力”

So, you'd need to implement your own upload behavior.因此,您需要实现自己的上传行为。 If that's not what you meant, id suggest using the needed props such as 'action' ('method', etc) to specify where the file should be uploaded to.如果这不是您的意思,id 建议使用所需的道具,例如“动作”(“方法”等)来指定文件应上传到的位置。

Below trick should work to set value to Form.Item for Upload inside Image Crop:下面的技巧应该可以将值设置为 Form.Item 以在 Image Crop 中上传:

import {
    Form,
    Upload,
} from 'antd';
import ImgCrop from 'antd-img-crop';
import axios from "axios";

const Upload = (props) => {
    const [form] = Form.useForm();

    const uploadImage = async options => {

        const { onSuccess, onError, file, onProgress, category } = options;

        const fmData = new FormData();
        const config = {
            headers: { "content-type": "multipart/form-data" },
            onUploadProgress: event => {
                const percent = Math.floor((event.loaded / event.total) * 100);
                onProgress({ percent: (event.loaded / event.total) * 100 }, file);
            }
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${API_DOMAIN}/upload`,
                fmData,
                config
            );
            onSuccess("ok", res);
            form.setFieldsValue({ photo: res.data.link })
        } catch (err) {
            console.log("Eroor: ", err);
            const error = new Error("Some error");
            onError({ err });
        }
    }
    return (
        <Form
            {...formItemLayout}
            form={form}
            name="form_name"
            onFinish={onFinish}
            scrollToFirstError
        >

            <Form.Item
                label="Photo"
                name="photo"
            >
                <ImgCrop rotate>
                    <Upload
                        name={'file'}
                        customRequest={uploadImage}
                        listType="picture-card"
                        onChange={onChange}
                        fileList={fileList}
                        onPreview={onPreview}
                        accept={"image/*"}
                    >
                        {fileList.length < 1 && '+ Upload'}
                    </Upload>
                </ImgCrop>
            </Form.Item>
        </Form>
    )

}

To use ImgCrop "antd-img-crop" with ant Form and Upload widget, and get the value with getFieldsValue() I made this code.要将 ImgCrop "antd-img-crop" 与 ant Form 和 Upload 小部件一起使用,并使用 getFieldsValue() 获取值,我编写了此代码。

import React, { useState } from 'react';
import BasePanel          from '@/containers/BasePanel';
import BaseFormComponent  from '@/formcomponents/BaseFormComponent';
import { Upload, Form, Button, Input, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
const { Option } = Select;

const CroppedInput = ({ value = {}, onChange }) => {
    const [fotos, setfotos] = useState([]);

    const triggerChange = (changedValue) => {
        onChange?.({
            fotos,
            ...value,
            ...changedValue,
        });
    };

    const onChange2 = (file) => {
        console.log(file);
        setfotos(file);

        triggerChange({
            fotos: file.fileList,
        });
    };

    return (
        <ImgCrop>
            <Upload listType="picture-card" maxCount={3} onChange={e => onChange2(e)}>
                <UploadOutlined />
            </Upload>
        </ImgCrop>
    );
};


class FormMultiImage extends BaseFormComponent{
    constructor(props) {
        super(props);

        this.checkValidator = this.checkValidator.bind(this);
    }

    checkValidator (_, value) {
        if (value !== undefined && value.fotos.length > 0) {
            return Promise.resolve();
        }
        return Promise.reject(new Error('Por favor seleccione una imagen'));
    };

    render() {
        return (
            <div>
                <Form.Item
                    label={"label"}
                    name={"name"}
                    rules={[
                        {
                            validator: this.checkValidator,
                        },
                    ]}
                >
                    <CroppedInput />
                </Form.Item>
            </div>
        );
    }
}

export default FormMultiImage;

And call it in your form并以您的形式调用它

<Form>
    <FormMultiImage />
</Form>
import React, { useState } from 'react';
import BasePanel          from '@/containers/BasePanel';
import BaseFormComponent  from '@/formcomponents/BaseFormComponent';
import { Upload, Form, Button, Input, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
const { Option } = Select;

const CroppedInput = ({ value = {}, onChange }) => {
    const [fotos, setfotos] = useState([]);

    const triggerChange = (changedValue) => {
        onChange?.({
            fotos,
            ...value,
            ...changedValue,
        });
    };

    const onChange2 = (file) => {
        console.log(file);
        setfotos(file);

        triggerChange({
            fotos: file.fileList,
        });
    };

    return (
        <ImgCrop>
            <Upload listType="picture-card" maxCount={3} onChange={e => onChange2(e)}>
                <UploadOutlined />
            </Upload>
        </ImgCrop>
    );
};


class FormMultiImage extends React.Component{
    constructor(props) {
        super(props);

        this.checkValidator = this.checkValidator.bind(this);
    }

    checkValidator (_, value) {
        if (value !== undefined && value.fotos.length > 0) {
            return Promise.resolve();
        }
        return Promise.reject(new Error('Por favor seleccione una imagen'));
    };

    render() {
        return (
            <div>
                <Form.Item
                    label={"label"}
                    name={"name"}
                    rules={[
                        {
                            validator: this.checkValidator,
                        },
                    ]}
                >
                    <CroppedInput />
                </Form.Item>
            </div>
        );
    }
}

export default FormMultiImage;

And call it in your form并以您的形式调用它

<Form>
    <FormMultiImage />
</Form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM