当使用Ant Design的Upload组件实现多文件上传时,beforeUploadHandler函数会被每个选中的文件调用一次。如果您只想获取一次选中的文件而不是每个文件都触发一次处理逻辑,可以采取以下方法:
使用 useRef 钩子保存文件列表:可以使用React的useRef钩子在组件中保存一个文件列表变量,而不是使用useState。这样就可以确保文件列表只在初始选择文件时获取一次。示例代码如下:
import { Upload, Button } from 'antd';
import { useRef } from 'react';
const App = () => {
const fileListRef = useRef([]);
const beforeUploadHandler = (file) => {
if (fileListRef.current.length === 0) {
fileListRef.current.push(file);
}
return false; // 返回 false 阻止文件上传
};
return (
<div>
<Upload
beforeUpload={beforeUploadHandler}
fileList={fileListRef.current}
>
<Button>选择文件</Button>
</Upload>
</div>
);
};
export default App;
在上述示例中,通过useRef创建了一个fileListRef引用变量来保存文件列表,只在第一次选择文件时获取选中的文件,之后不再改变。