目录

How do I set the width of a child component so that it does not exceed the size of its parent component?

Use the calc() function to calculate and dynamically set the width of the child component. The code snippet is as follows:

@Entry
@Component
struct SizeExample {
  @State flag:boolean = true;

  build() {
    Row() {
      Text(this.flag ? 'Followed by' : 'Not following')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .backgroundColor(0xFFFAF0)
        .textAlign(TextAlign.Center)
        .margin(10)
        .size({ width: this.flag ? 60 : 80 })
        .onClick(()=>{
          this.flag = !this.flag
        })
      Text('HarmonyOS Developer Community')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .backgroundColor(0xFFFAF0)
        .size({width: this.flag ? 'calc(100% - 60vp)' : 'calc(100% - 80vp)'})
    }
    .width(500)
    .margin({ top: 5 })
  }
}

Reference

Size