使用flex弹性布局即可,可参考以下示例:@Entry @Component export struct SearchBox { controller: SearchController = new SearchController() @State searchHistoryArray: string[] = ['矢量图','大黄蜂11号','老顽童','成人保险怎么选呢,我也不知道啊'] 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, (item: string) => { Row() { Text(item + ' ').margin({ top: 2, bottom: 2 }).textAlign(TextAlign.Center) .fontSize(13) }.backgroundColor('#ff9696d9') .borderStyle(BorderStyle.Solid) .borderRadius(15) .margin(10) .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) } } }
使用flex弹性布局即可,可参考以下示例: