軟件環境
- macOS Big Sur 11.1
- React 16.12.0
- Ant Design 4.10.0
實際效果
現有一個需求,是上傳文件,點擊瀏覽文件按鈕,選中文件後,在按鈕的上方顯示,上傳的文件列表,如下圖所示
當前效果
目前使用阿里的Ant UI組件庫,使用其中的上傳組件,官方提供的示例,如下圖如示
本地使用後,如下圖所示
如何才能實現,我們需要的效果呢,Google了好多文章,找到了一種方式,就是重寫itemRender方法,自定義文件列表的展示,使用這個方法,需要重寫多個action。
後來查看公司前端人員寫的代碼,看到另一種解決方法。
主要使用兩個Upload組件,第一個Upload組件主要是展示文件列表,第二個Upload組件是選擇文件上傳的這個操作,不過,選擇文件後,把文件列表在下方展示隱藏起來。
showUploadList: false, //不顯示上傳的列表
把得到的文件列表,賦值給第一個Upload組件中,大概如下:
beforeUpload(file: any, fileList: any) {
setFileList(fileList); //設置文件列表
return false; //不要調用上傳文件接口
},
<!--第一個Upload組件-->
<Upload fileList={fileList}></Upload>
部分代碼如下:
<StyleContent>
<StyleMainContent>
<Button onClick={btnOnClick} type="primary">打開上傳</Button>
<Modal visible={isVisible} title="上傳附件" footer={[]} closable>
<div style={{ border: '1px solid #ccc', height: 150, marginBottom: 10 }}>
<Upload fileList={fileList} onChange={onChange}></Upload>
</div>
<div style={{ textAlign: 'right' }}>
<Upload {...updateProps} ><Button type="primary">瀏覽文件</Button></Upload>
<Button style={{marginLeft:2}} onClick={() => { setIsVisible(false) }}>關閉</Button>
</div>
</Modal>
</StyleMainContent>
</StyleContent>
const [isVisible, setIsVisible] = useState(false);
const [fileList, setFileList] = useState([]);
const btnOnClick = () => {
setIsVisible(true);
}
const updateProps = {
name: 'file',
beforeUpload(file: any, fileList: any) {
setFileList(fileList);
return false;
},
showUploadList: false,
styly: {
display: 'inline-block'
}
}
const onChange = ({ file, fileList }: { file: any; fileList: any }) => {
console.log(file, fileList);
setFileList(fileList);
};