antd react 文件上传只允许上传一个文件且上传后隐藏上传按钮

antd react 文件上传只允许上传一个文件且上传后隐藏上传按钮

效果图


代码解析

javascript 复制代码
import { Form, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { BASE_URL } from '@/utils/request';
const FormItemInputUpload = (props) => {
  const [visble, setVisibel] = useState(false);

  useEffect(() => {
    if (props.edit) {
      setVisibel(true);
    } else {
      setVisibel(false);
    }
  }, [props]);

  const normFile = (e) => {
    if (e.fileList && e.fileList.length == 0) {
      setVisibel(false);
    } else {
      setVisibel(true);
    }
    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 || 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}
      >
        {visble ? null : <PlusOutlined />}
      </Upload>
    </Form.Item>
  );
};

export default FormItemInputUpload;



···
//引用
          <FormItemInputUpload
              name="image"
              label="图片"
              edit={props?.fillingForm?.image}
              form={form}
              sysType="SIGNATURE"
              rules
            />
相关推荐
众生回避3 分钟前
鸿蒙ms参考
前端·javascript·vue.js
洛千陨3 分钟前
Vue + element-ui实现动态表单项以及动态校验规则
前端·vue.js
笃励40 分钟前
Angular面试题五
javascript·ecmascript·angular.js
GHUIJS1 小时前
【vue3】vue3.5
前端·javascript·vue.js
-seventy-1 小时前
对 JavaScript 原型的理解
javascript·原型
&白帝&1 小时前
uniapp中使用picker-view选择时间
前端·uni-app
魔术师卡颂1 小时前
如何让“学源码”变得轻松、有意义
前端·面试·源码
谢尔登1 小时前
Babel
前端·react.js·node.js
ling1s1 小时前
C#基础(13)结构体
前端·c#
卸任2 小时前
使用高阶组件封装路由拦截逻辑
前端·react.js