Ant Design 的 Upload 組件是 React 生態中廣泛使用的文件上傳解決方案,它提供了豐富的 API 和默認樣式。但在實際開發中,我們經常需要自定義文件列表的展示位置,以滿足特定的 UI 需求。
默認情況下,Upload 組件會在組件下方自動渲染文件列表:
<Upload {...props}>
<Button icon={<UploadOutlined />}>點擊上傳</Button>
</Upload>
這種布局方式雖然簡單,但在以下場景中可能不適用: - 需要將文件列表展示在表單的其他位置 - 需要將多個上傳組件的文件列表合并展示 - 需要實現更復雜的文件列表交互
const [fileList, setFileList] = useState([]);
const handleChange = ({ fileList }) => {
setFileList(fileList);
};
return (
<div>
<Upload fileList={fileList} onChange={handleChange}>
<Button icon={<UploadOutlined />}>上傳文件</Button>
</Upload>
{/* 自定義文件列表位置 */}
<div className="custom-file-list">
{fileList.map(file => (
<div key={file.uid}>{file.name}</div>
))}
</div>
</div>
);
<Upload
fileList={fileList}
onChange={handleChange}
showUploadList={false} // 禁用默認列表
>
<Button icon={<UploadOutlined />}>上傳文件</Button>
</Upload>
{/* 完全自定義的列表渲染 */}
<Table
dataSource={fileList}
columns={[
{ title: '文件名', dataIndex: 'name' },
{ title: '大小', render: file => formatFileSize(file.size) },
{ title: '操作', render: file => (
<Button onClick={() => handleRemove(file)}>刪除</Button>
)}
]}
/>
跨組件共享文件列表:通過狀態管理工具(Redux/MobX)共享 fileList 狀態
分區域上傳:
// 上傳區域
<Upload {...props}>
<div className="upload-area">拖拽文件到此處</div>
</Upload>
// 展示區域(可能在另一個組件中)
<FilePreview files={fileList} />
通過以上方法,你可以靈活控制 Upload 組件的文件列表展示位置,滿足各種復雜的業務場景需求。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。