react+antd 封装图片上传组件。

问题描述:因antd本身缺陷,我们上传成功后,再次删除后,系统会默认为已经上传,导致不为空验证失效。

import { Form, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import { BASE_URL } from '@/utils/request';
const FormItemInputUpload = (props) => {
  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const onRemove = (e) => {
    const urls = [props.form.getFieldValue(props.name)]
      .flat()
      .filter((item) => item != e.response.data[0].imageAddress);
    props.form.setFieldsValue({
      [props.name]: urls,
    });
  };
  return (
    <Form.Item
      label={props.label}
      name={props.name}
      valuePropName="fileList"
      getValueFromEvent={normFile}
      rules={
        props?.rules && [
          {
            required: true,
            validator: (_, value, callback) => {
              if (value.length == 0) {
                callback(`请上传${props.label}`);
              } else {
                callback();
              }
            },
          },
        ]
      }
    >
      <Upload
        maxCount={props?.maxCount || 1}
        action={`${BASE_URL}/cdsj-file/upload`}
        data={{ minioCatalogEnums: props.sysType }}
        name="files"
        headers={{ Authorization: localStorage.getItem('token') }}
        listType="picture-card"
        accept=".png,.jpeg,.jpg"
        beforeUpload={(file) => {
          const isPNG =
            file.type == 'image/png' ||
            file.type == 'image/jpg' ||
            file.type == 'image/jpeg';
          if (!isPNG) {
            message.error('请上传图片格式文件!');
          }
          return isPNG || Upload.LIST_IGNORE;
        }}
        onRemove={onRemove}
      >
        <PlusOutlined />
      </Upload>
    </Form.Item>
  );
};

export default FormItemInputUpload;

你可能感兴趣的:(react.js,javascript,ecmascript)