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
/>