如何设置子组件宽度使其不超过父组件的大小?

如何设置子组件宽度使其不超过父组件的大小

阅读 322
1 个回答

可以使用尺寸设置中的calc计算属性,对子组件的宽度进行判断,来设置子组件宽度。参考代码如下:

@Entry 
@Component 
struct SizeExample { 
  @State flag:boolean = true; 
 
  build() { 
    Row() { 
      Text(this.flag ? '已关注' : '没有关注') 
        .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开发者社区') 
        .fontSize(20) 
        .fontWeight(FontWeight.Bold) 
        .backgroundColor(0xFFFAF0) 
        .size({width: this.flag ? 'calc(100% - 60vp)' : 'calc(100% - 80vp)'}) 
    }.width(500).margin({ top: 5 }) 
  } 
}

参考链接:

尺寸设置

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进