搜索高亮目前官方也没有可以现成的组件,但是需求来了,怎么办,只能摸索着自己写一个
目前官方API中最接近的应该是 richText组件了,富文本组件,当然可以实现,但是有不少问题
1.大小调整太麻烦,跟组件各个不入,除非整屏都用richText,才看不出来,否则样式很难看
2.用richText显示的内容区域不支持滚动(页不是不支持,就是list自带的上拉下拉都不行,只能通过onTouch事件去写,但是那也太麻烦了)
基于上面两点,放弃这个组件,那就只能使用基础组件来实现了
先看下效果
搜索高亮展示
代码实现:
//检索关键字,并返回选中的歌曲,value=需要高亮的字,list=歌曲数组
static lineHigh(value: string, itemList: songClass[]) {
const searchList: songClass[] = []
itemList.some((item: songClass) => {
if (item.name.includes(value) || item.author.includes(value)) {
searchList.unshift(item)
}
})
return searchList
}
songClass = 歌曲对象,自己可替换成自己的对象
该方法传入 搜索关键词,被搜索对象数组,输出包含关键词的对象数组
应该在点击搜索后调用
页面代码
//拿值去匹配 歌曲列表,全量 value=搜索关键词
getSearchByValue(value: string) {
this.searchList = CommUtils.lineHigh(value, this.menuItem.songList)
}
Search({
value: this.textValue,
//placeholder: '搜索你想找的音乐',
controller: this.searchController
})
.backgroundColor('#F3F3FA')
.onChange((value: string) => {
value = value.replace(/\s+/g, '')
this.textValue = value.replace(/\s+/g, '')
if (this.textValue !== '') {
this.isShowList = Visibility.Visible
//拿值去匹配 歌曲列表,全量
this.getSearchByValue(this.textValue)
} else {
this.isShowList = Visibility.None
}
})
.textAlign(TextAlign.Start)
.height(30)
.borderRadius(60)
this.textValue = 搜索关键词
this.searchController = 搜索组件Controller
this.isShowList = 搜索结果是否显示
搜索结果区域
....
Text(){
ForEach(item.name.split(''),(itemStr:string)=>{
Span(itemStr)
.fontColor(this.textValue.includes(itemStr) || item.id === this.PlayState.id ?'#00AE68':'#000000')
.fontSize(15)
.fontWeight(FontWeight.Bold)
})
}.maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis })
....
关键思路在:
用text包裹要显示的结果,循环每一个字,如果 搜索关键词包含这个字,就用绿色显示
这样我们也就能用最基本的组件显示出搜索高亮的效果了