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
            />
相关推荐
JarvanMo15 分钟前
借助FlutterFire CLI实现Flutter与Firebase的多环境配置
前端·flutter
Jedi Hongbin29 分钟前
echarts自定义图表--仪表盘
前端·javascript·echarts
凯哥197033 分钟前
Sciter.js指南 - 桌面GUI开发时使用第三方模块
前端
边洛洛33 分钟前
对Electron打包的exe文件进行反解析
前端·javascript·electron
财神爷亲闺女34 分钟前
js 实现pc端鼠标横向拖动滚动
前端
用户20311966009634 分钟前
sheet在SwiftUI中的基本用法
前端
晴殇i35 分钟前
一行代码搞定防抖节流:JavaScript新特性解析
前端·javascript
啊花是条龙36 分钟前
使用 Axios 和 AbortController 实现请求控制和取消
react.js·typescript