1 个回答

请参考以下代码:

@Entry
@Component
export struct SearchBox {
  controller: SearchController = new SearchController()
  @State searchHistoryArray: string[] = []
  private arrMax: number = 10
  @State inputValue: string = ""

  build() {
    NavDestination() {
      Column({ space: 10 }) {
        Search({ value: this.inputValue, placeholder: '请输入', controller: this.controller })
          .searchButton('搜索')
          .width('100%')
          .height(40)
          .backgroundColor('#F5F5F5')
          .placeholderColor(Color.Grey)
          .placeholderFont({ size: 14, weight: 400 })
          .textFont({ size: 14, weight: 400 })
          .onSubmit((value: string) => {
            this.insertOrUpdateItem(value === "" ? '' : value)
          })
          .margin({ top: 10, bottom: 10 })
          .borderRadius(0)

        Column() {
          Text('历史搜索').fontSize(18)
          Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap }) {
            ForEach(this.searchHistoryArray.slice().reverse(), (item: string) => {
              Row() {
                Text(item + '  ').margin({ top: 2, bottom: 2 }).textAlign(TextAlign.Center)
                  .fontSize(13)

              }.backgroundColor('#ff9696d9')
              .borderStyle(BorderStyle.Solid)
              .borderRadius(15)
              .margin(1)
              .height(30)
            })
          }

        }.width('100%').alignItems(HorizontalAlign.Start)

      }.width('100%').margin(10).constraintSize(
        { maxWidth: '100%' })
    }
  }

  insertOrUpdateItem(item: string) {
    const index = this.searchHistoryArray.indexOf(item)
    if (index !== -1) {
      this.searchHistoryArray.splice(index, 1)
      this.searchHistoryArray.push(item)
      return
    }
    if (this.searchHistoryArray.length < this.arrMax) {
      this.searchHistoryArray.push(item)
    } else {
      this.searchHistoryArray.shift()
      this.searchHistoryArray.push(item)
    }
    // todo 需要自行实现将本地的历史搜索数据写到数据库,然后定时的同步到云端
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进