React框架中Antd组件库应用
1.Upload组件
1.1 代码示例
import { useState } from 'react';
import { Button, Upload } from 'antd'; // 引入
import type { UploadProps } from 'antd'; // 引入上传类型
import type {UploadFile} from 'antd/es/upload/interface' // 引入数据类型
const UploadFiles = () => {
const [fileList,setFileList] = useState();
const props = {
action: "文件上传路径",
multiple: "是否可以上传多个文件",
fileList: fileList, // 已上传的文件列表
onChange(info) {
const {status} = info.file;
if(status === "uploading"){
setFileList(info.fileList);
};
if(status !== "uploading"){
let arr = [];
info.fileList.forEach((item)=>{
if(item.response){
arr.push(item.response);
}else{
arr.push(item);
}
})
setFileList([...arr]);
};
}
}
return (
<>
<Upload {...props}></Upload>
</>
)
}
export default UploadFiles
1.2 难点
【fileList】:已上传的文件列表(受控),使用此参数时,如果遇到 onChange 只会调用一次
onChange 只调用一次,就会面临返回的 info.file 中的 status 属性为 uploading,文件详细属性 response 也是不存在
1.3 解决方案
只要 fileList 被重新赋值,onChange 就可以被重新调用,重新调用之后,返回的 info.file 中 status 属性为 done ,response 属性也会返回
if(status === "uploading"){
setFileList(info.fileList);
};