鸿蒙原生开发手记:徒步迹 - 路线搜索与筛选功能
·

鸿蒙原生开发手记:徒步迹 - 路线搜索与筛选功能
实现多条件搜索和标签筛选
一、前言
搜索和筛选是列表页的核心交互。本文实现路线列表的搜索框实时搜索和难度标签筛选功能。
二、搜索框实现
@Component
struct SearchBar {
@State query: string = '';
@State isSearching: boolean = false;
build() {
Row() {
TextInput({
placeholder: '搜索路线名称或地点',
text: this.query,
})
.layoutWeight(1)
.backgroundColor(Color.Transparent)
.fontSize(14)
.onChange((value: string) => {
this.query = value;
this.onSearch(value);
});
if (this.isSearching) {
LoadingProgress().width(18).height(18).margin({ right: 12 });
}
}
.width('100%')
.height(44)
.backgroundColor('#FFF')
.borderRadius(22)
.padding({ left: 16 });
}
onSearch(query: string): void {
this.isSearching = true;
// debounce 搜索
setTimeout(() => {
AppStorage.setOrCreate('routeQuery', query);
this.isSearching = false;
}, 300);
}
}
三、筛选标签
@Component
struct FilterTags {
@State selectedTag: string = '全部';
private tags: string[] = ['全部', '简单', '中等', '困难'];
build() {
Row() {
ForEach(this.tags, (tag: string) => {
Text(tag)
.fontSize(13)
.fontColor(this.selectedTag === tag ? Color.White : '#666')
.backgroundColor(
this.selectedTag === tag ? '#4CAF50' : '#FFF'
)
.borderRadius(16)
.padding({ left: 16, right: 16, top: 6, bottom: 6 })
.margin({ right: 8 })
.onClick(() => {
this.selectedTag = tag;
AppStorage.setOrCreate('routeDifficulty', tag);
});
}, (tag: string) => tag);
}
.padding({ left: 16, right: 16 });
}
}
四、组合搜索与筛选
function filterRoutes(
routes: HikingRoute[],
query: string,
difficulty: string
): HikingRoute[] {
return routes.filter(route => {
// 关键词匹配
const matchQuery = !query ||
route.name.includes(query) ||
route.description.includes(query) ||
route.tags.some(t => t.includes(query));
// 难度筛选
const matchDifficulty = difficulty === '全部' ||
route.difficulty === difficulty;
return matchQuery && matchDifficulty;
});
}
五、总结
搜索框结合筛选标签,让用户可以快速找到感兴趣的路线。实时搜索配合 debounce 优化,确保交互流畅。
下一篇文章实现路线详情页布局。
下一篇预告:鸿蒙原生开发手记:徒步迹 - 路线详情页布局实现
更多推荐


所有评论(0)