HarmonyOS 如何在Text中做搜索词高亮?

搜索框中输入文字, 搜索之后服务器返回的数据 包含搜索词的文字要设置成高亮展示 怎么实现?

阅读 624
1 个回答

可以参考此文档:

https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/ui/arkts-common-components-text-display.md/

使用span来高亮展示你所需要的文字。

class formatS { //定义为解析后的标签内容数组,str是要显示的内容,isAim为是否高亮标志 
  char: string = ""; 
  isAim: boolean = false; 
} 
 
@Entry 
@Component 
struct Index { 
  @State sourceStr: string = '几点睡啊你好吗几点睡啊你好吗你好吗几点睡啊你好吗你好吗几几点睡啊点'; 
  @State formatStr: formatS[] = [] 
 
  processSource(str: string): formatS[] { 
    let result: formatS[] = [] 
 
    const regex1 = RegExp('几点睡啊', 'g'); 
    let indexList: number[] = [] 
    let array: RegExpExecArray | null = null 
    while ((array = regex1.exec(str)) !== null) { 
      console.log(`start: ${array.index},Found ${array[0]}.end ${regex1.lastIndex - 1}.`); 
      indexList.push(array.index, regex1.lastIndex - 1) 
    } 
 
    let cache = "" 
    for (let index = 0; index < str.length; index++) { 
      if (!indexList.includes(index)) { 
        cache = cache + str[index] 
        if (index > indexList[indexList.length-1] && index === str.length - 1) { 
          result.push({ 
            char: cache, 
            isAim: false 
          }) 
        } 
      } else { 
        result.push({ 
          char: cache, 
          isAim: false 
        }) 
        result.push({ 
          char: "几点睡啊", 
          isAim: true 
        }) 
        index = index + "几点睡啊".length - 1 
        cache = "" 
      } 
    } 
 
    return result 
  } 
 
  build() { 
    Column() { 
      ForEach(this.processSource(this.sourceStr), (item: formatS) => { 
        if (item.isAim) { 
          Text(item.char).fontSize(20).fontColor(Color.Red); //对目标内容进行高亮处理 
        } else { 
          Text(item.char).fontSize(20); 
        } 
      }) 
    }.width('100%').height('100%') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进