react+ant框架上传组件+form表单组件实现点击新增表单项上传组件的图片各自独立

import React, { useState } from 'react';
import { Form, Row, Col, Select, Input, Upload, Button, Image, Space } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';

const { Option } = Select;

const eduOptions = [
  { label: '小学', value: 'primary' },
  { label: '初中', value: 'middle' },
  { label: '高中', value: 'high' },
];

const eduNatureOptions = [
  { label: '全日制', value: 'full-time' },
  { label: '非全日制', value: 'part-time' },
];

const EducationForm = () => {
  const [form] = Form.useForm();
  const [fields, setFields] = useState([]);
  const [imageLists, setImageLists] = useState([]);

  const handleUpload = ({ file, field }) => {
    // 处理图片上传逻辑
    const reader = new FileReader();
    reader.onload = (e) => {
      const imageUrl = e.target.result;
      const fieldIndex = fields.findIndex((f) => f.name === field.name);
      setImageLists((prevImageLists) => {
        const newImageLists = [...prevImageLists];
        newImageLists[fieldIndex] = [...(newImageLists[fieldIndex] || []), imageUrl];
        return newImageLists;
      });
    };
    reader.readAsDataURL(file);
  };

  const handlePreview = (file) => {
    // 预览图片
    const previewWindow = window.open();
    previewWindow.document.write(`<img src="${file.url || file.preview}" style="max-width: 100%;" />`);
  };

  const handleRemove = (fieldIndex, imageIndex) => {
    // 移除图片
    setImageLists((prevImageLists) => {
      const newImageLists = [...prevImageLists];
      newImageLists[fieldIndex].splice(imageIndex, 1);
      return newImageLists;
    });
  };

  const onFinish = (values) => {
    // 将imageLists添加到对应字段
    const formData = { ...values };
    fields.forEach((field, fieldIndex) => {
      const fieldName = field.name;
      formData[fieldName].images = imageLists[fieldIndex] || [];
    });

    console.log(formData);
    console.log(imageLists);
  };

  const add = () => {
    const field = {
      name: Date.now(),
    };
    setFields((prevFields) => [...prevFields, field]);
    setImageLists((prevImageLists) => [...prevImageLists, []]);
  };

  const remove = (index) => {
    setFields((prevFields) => {
      const newFields = [...prevFields];
      newFields.splice(index, 1);
      return newFields;
    });
    setImageLists((prevImageLists) => {
      const newImageLists = [...prevImageLists];
      newImageLists.splice(index, 1);
      return newImageLists;
    });
  };

  const renderEducationFields = () => {
    return (
      <>
        {fields.map((field, fieldIndex) => (
          <div key={field.name}>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item
                  name={[field.name, 'startEndTime']}
                  label="时间"
                  labelCol={{ span: 24 }}
                  rules={[{ required: true, message: '请选择时间' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  name={[field.name, 'education']}
                  label="学历层次"
                  labelCol={{ span: 24 }}
                  rules={[{ required: true, message: '请选择学历层次' }]}
                >
                  <Select>
                    {eduOptions.map((option) => (
                      <Option value={option.value} key={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  name={[field.name, 'nature']}
                  label="学历性质"
                  labelCol={{ span: 24 }}
                  rules={[{ required: true, message: '请选择学历性质' }]}
                >
                  <Select>
                    {eduNatureOptions.map((option) => (
                      <Option value={option.value} key={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  name={[field.name, 'major']}
                  label="所学专业"
                  labelCol={{ span: 24 }}
                  rules={[{ required: true, message: '请输入所学专业' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16} justify="end" align="middle">
              <Col span={1}>
                {fields.length > 1 && (
                  <MinusCircleOutlined onClick={() => remove(fieldIndex)} />
                )}
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Upload
                  name="image"
                  listType="picture-card"
                  fileList={imageLists[fieldIndex]?.map((image, imageIndex) => {
                    return {
                      uid: `${fieldIndex}-${imageIndex}`,
                      url: image,
                    };
                  })}
                  customRequest={({ file }) => handleUpload({ file, field })}
                  onPreview={handlePreview}
                  onRemove={() => handleRemove(fieldIndex)}
                >
                  {imageLists[fieldIndex]?.length >= 3 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传</div>
                    </div>
                  )}
                </Upload>
              </Col>
            </Row>
          </div>
        ))}
        <Form.Item wrapperCol={{ span: 24 }}>
          {fields.length < 5 && ( // 最多允许上传5个学历信息
            <Button
              type="dashed"
              onClick={add}
              block
              icon={<PlusOutlined />}
              style={{ height: '100px', marginTop: '16px' }}
            >
              添加学历信息
            </Button>
          )}
        </Form.Item>
      </>
    );
  };

  return (
    <Form form={form} onFinish={onFinish}>
      {renderEducationFields()}

      <Form.Item wrapperCol={{ span: 24 }}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default EducationForm;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值