🎯 目标
封装一个多功能文件管理组件 FileManager
,适用于:
- 展示本地/远程文件与文件夹结构
- 支持目录展开、文件预览、重命名、移动、删除等操作
- 多选操作:批量移动 / 删除 / 下载
- 文件类型图标支持(图片、视频、文档、压缩包等)
- 可与实际文件系统、云接口结合使用
🧱 样式结构示意
📁 我的资料
├── 📄 简历.pdf [预览] [删除]
├── 📷 头像.jpg [查看] [重命名]
└── 📁 作品集
├── 🖼 图1.png
└── 🖼 图2.png
🧰 组件实现:FileManager.ets(静态模拟结构)
@Component
export struct FileManager {
@Prop tree: Array<FileItem> = []
@Prop onOpen: (file: FileItem) => void = () => {}
@Prop onDelete: (file: FileItem) => void = () => {}
@Prop onRename: (file: FileItem) => void = () => {}
build() {
Column({ space: 4 }).padding(12) {
this.tree.forEach(item => this.renderItem(item, 0))
}
}
private renderItem(item: FileItem, level: number) {
Column() {
Row()
.padding({ top: 6, bottom: 6, left: 8 + level * 16, right: 8 })
.backgroundColor('#fdfdfd')
.borderRadius(6)
.justifyContent(FlexAlign.SpaceBetween)
.alignItems(VerticalAlign.Center) {
Row({ space: 6 }).alignItems(VerticalAlign.Center) {
Text(this.getIcon(item))
Text(item.name).fontSize(14).fontColor('#333')
}
Row({ space: 8 }) {
if (!item.isDir) {
Button('打开').type(ButtonType.Normal).fontSize(12).onClick(() => this.onOpen(item))
}
Button('重命名').type(ButtonType.Normal).fontSize(12).onClick(() => this.onRename(item))
Button('删除').type(ButtonType.Normal).fontSize(12).onClick(() => this.onDelete(item))
}
}
if (item.isDir && item.children) {
item.children.forEach(child => this.renderItem(child, level + 1))
}
}
}
private getIcon(item: FileItem): string {
if (item.isDir) return '📁'
if (item.name.endsWith('.jpg') || item.name.endsWith('.png')) return '🖼'
if (item.name.endsWith('.pdf')) return '📄'
if (item.name.endsWith('.zip')) return '🗜'
return '📄'
}
}
export interface FileItem {
name: string
isDir: boolean
children?: FileItem[]
}
📦 使用示例
@Entry
@Component
struct DemoFileManager {
private files: FileItem[] = [
{
name: '我的资料', isDir: true, children: [
{ name: '简历.pdf', isDir: false },
{ name: '头像.jpg', isDir: false },
{
name: '作品集', isDir: true, children: [
{ name: '图1.png', isDir: false },
{ name: '图2.png', isDir: false }
]
}
]
}
]
build() {
FileManager({
tree: this.files,
onOpen: file => ToastManager.show(`打开:${file.name}`),
onDelete: file => ToastManager.show(`删除:${file.name}`, 'warning'),
onRename: file => ToastManager.show(`重命名:${file.name}`, 'info')
})
}
}
✨ 可扩展能力建议
功能 | 说明 |
---|---|
拖拽移动文件 / 文件夹 | 拖拽目标后触发 move 事件处理 |
多选操作模式 | 开启勾选框,支持批量操作(移动/删除) |
接入真实文件系统或云 API | 支持文件增删查改,或云盘同步操作 |
搜索 + 文件类型筛选 | 输入关键字或类型过滤(如仅显示图片、仅PDF) |
📘 下一篇预告
第48篇:【HarmonyOS 5.0.0 或以上】构建多语言切换组件 I18nSwitcher:支持语言配置 / 自动刷新文本 / 本地缓存