Text匹配文字高亮显示

在搜索框中搜索想要的文字,Text就回进行匹配,并且高亮显示。

HarmonyOS
2024-05-26 15:18:50
3158浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
cbaby

使用的核心API

Text

核心代码解释

@Entry 
@Component 
struct Page240108114409062 { 
  @State searchValue: string = ''; 
  @State dataArr: string[] = [ 
    "第一段数据", 
    "第二段数据", 
    "第三段数据", 
    "第四段数据", 
    "第五段数据", 
    "第六段数据", 
    "第七段数据", 
    "第八段数据", 
    "第九段数据", 
    "第十段数据", 
  ] 
  @State showArr: string[] = [] 
 
  build() { 
    Row() { 
      Column() { 
        Search({ value: $$this.searchValue, placeholder: 'Type to search...' }) 
          .searchButton('SEARCH') 
          .width('90%') 
          .height(40) 
          .backgroundColor('#F5F5F5') 
          .placeholderColor(Color.Grey) 
          .placeholderFont({ size: 14, weight: 400 }) 
          .textFont({ size: 14, weight: 400 }) 
          .margin(20) 
          .onChange(() => { 
            this.showArr = this.dataArr.filter((item: string) => { 
              return this.searchValue && item.indexOf(this.searchValue) != -1 
            }) 
            console.log(JSON.stringify(this.showArr)) 
          }) 
        List() { 
          ForEach(this.showArr, (item: string) => { 
            ListItem() { 
              Row() { 
                // RichText(item) 
                Text() { 
                  Span(this.searchValue).fontColor(Color.Red) 
                  Span(item.replace(this.searchValue, "")) 
                } 
              }.width("100%").height(40).justifyContent(FlexAlign.Center) 
            } 
          }) 
        } 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.

注明适配的版本信息

  • IDE版本:4.1.3.500
  • SDK版本:4.1.5.6

实现效果

分享
微博
QQ
微信
回复
2024-05-27 20:22:35
相关问题
HarmonyOS Text部分文字高亮设置
920浏览 • 1回复 待解决
HarmonyOS 怎么高亮显示搜索的文字
934浏览 • 1回复 待解决
HarmonyOS Text搜索关键字高亮功能
1844浏览 • 1回复 待解决
HarmonyOS 如何在Text中做搜索词高亮?
1086浏览 • 1回复 待解决
HarmonyOS Text组件如何设置文字方向
673浏览 • 1回复 待解决
如何识别文本中的邮箱并高亮显示
1128浏览 • 1回复 待解决
text怎么更改部分文字颜色
8035浏览 • 1回复 待解决
HarmonyOS 文字显示问题
996浏览 • 1回复 待解决
HarmonyOS Text显示异常
511浏览 • 1回复 待解决
文字背景颜色渐变显示
2873浏览 • 1回复 待解决
HarmonyOS Text组件是否支持文字描边
860浏览 • 1回复 待解决
鸿蒙 | Text 内容显示问题
11148浏览 • 5回复 待解决
如何获取Text组件中文字的宽度
3157浏览 • 1回复 待解决