React+AntD实现文件上传数量限制及单次错误提示
解决方案:单次错误提示+文件数量上传限制
问题根源在于beforeUpload会对每个选中的文件单独执行一次,一次性选11个文件就会触发11次错误提示。我们可以通过一个标记变量来控制提示仅触发一次,同时在合适时机重置标记以支持后续操作。
具体实现步骤
- 引入标记变量:使用
useRef(函数组件)存储是否已显示过数量超限提示(ref更新不会触发组件重渲染,更适合此场景)。 - 修改
beforeUpload逻辑:仅当标记未激活时显示错误提示,之后激活标记避免重复触发。 - 重置标记:在文件列表更新时(
onChange事件)重置标记,确保下次选择文件时能正常触发提示。
完整代码示例
import { useRef } from 'react'; import { Upload, message } from 'antd'; // 假设使用Ant Design组件库 const YourUploadComponent = () => { // 用于标记是否已显示过数量超限提示 const hasShownLimitError = useRef(false); const beforeUpload = (file, fileList) => { const maxFileSize = 250 * 1024 * 1024; // 250MB限制 const maxLimit = 10; // 处理文件数量超限逻辑 if (fileList.length > maxLimit) { if (!hasShownLimitError.current) { message.error(`Only 10 files allowed`); hasShownLimitError.current = true; } return false; } // 处理文件大小超限逻辑 if (file.size > maxFileSize) { message.error(`${file.name} file upload failed (exceeds 250MB)`); console.error("File size exceeds the limit of 250MB"); return false; } return true; }; // 文件列表更新时重置提示标记 const handleUploadChange = () => { hasShownLimitError.current = false; }; // 自定义上传逻辑(原代码中的handleFileUpload) const handleFileUpload = (options) => { // 你的上传实现 }; return ( <Upload.Dragger multiple beforeUpload={beforeUpload} customRequest={handleFileUpload} showUploadlist={false} onChange={handleUploadChange} > {/* 拖拽区域内容 */} <p className="ant-upload-drag-icon"> <InboxOutlined /> </p> <p className="ant-upload-text">Click or drag file to this area to upload</p> </Upload.Dragger> ); }; export default YourUploadComponent;
类组件适配方案
如果使用类组件,可将标记存储为实例属性:
class YourUploadComponent extends React.Component { constructor(props) { super(props); this.hasShownLimitError = false; } beforeUpload = (file, fileList) => { const maxFileSize = 250 * 1024 * 1024; const maxLimit = 10; if (fileList.length > maxLimit) { if (!this.hasShownLimitError) { message.error(`Only 10 files allowed`); this.hasShownLimitError = true; } return false; } if (file.size > maxFileSize) { message.error(`${file.name} file upload failed (exceeds 250MB)`); console.error("File size exceeds the limit of 250MB"); return false; } return true; }; handleUploadChange = () => { this.hasShownLimitError = false; }; handleFileUpload = (options) => { // 你的上传实现 }; render() { return ( <Upload.Dragger multiple beforeUpload={this.beforeUpload} customRequest={this.handleFileUpload} showUploadlist={false} onChange={this.handleUploadChange} > {/* 拖拽区域内容 */} </Upload.Dragger> ); } }
内容的提问来源于stack exchange,提问作者Aravind Ashokkumar
相关产品推荐
相关产品推荐

