HarmonyOS text组件和其他组件使用row包裹,text组件会超出组件本身大小?

demo如下,不能用layoutweight(1),因为内容少的时候需要整体居中

@Entry
@Component
struct Index {
  build() {
    Row() {
      Image($r('app.media.startIcon'))
        .width(40)
      Text('啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊')
    }
    .margin(20)
    .justifyContent(FlexAlign.Center)
  }
}
阅读 539
1 个回答

参考如下demo

import { display } from '@kit.ArkUI';

@Entry
@Component
struct Index20 {
  @State message:string = '啊啊啊'
  @State screenWidthPx:number = 0
  aboutToAppear(): void {
    this.screenWidthPx = display.getDefaultDisplaySync().width;
  }
  build() {
    Column() {
      Button('加数据')
        .onClick(()=>{
          if(this.message.length > 20){
            this.message = '啊啊啊啊啊啊啊啊啊啊啊'
          }
          else {
            this.message = '啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊'
          }
        })
      Row() {
        Image($r('app.media.startIcon'))
          .width(40)
        Text(this.message)
          .backgroundColor(Color.Red)
          .constraintSize({ maxWidth: px2vp(this.screenWidthPx) - 20 -20 - 40 })
      }
      .width('100%')
      .margin(20)
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
    .width('100%')
  }
}