1. 固定高度设置
直接指定容器的绝对或相对高度值:
RelativeContainer() {
// 子组件...
}
.width('100%')
.height(200) // 固定高度 200vp
.backgroundColor('#F0F0F0')
2. 百分比高度
基于父容器高度的百分比自适应:
RelativeContainer() {
// 子组件...
}
.width('80%')
.height('60%') // 父容器高度的 60%
.margin({ top: 20 })
3. 最大/最小高度限制
通过 constraintSize 设置高度范围,防止布局溢出:
RelativeContainer() {
// 子组件...
}
.constraintSize({
minHeight: 100, // 最小高度 100vp
maxHeight: 500 // 最大高度 500vp
})
4. 内容自适应高度
使用 wrapContent 让容器高度根据子组件自动调整:
RelativeContainer() {
Text('自适应内容高度')
.fontSize(20)
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
})
}
.width('100%')
.height('wrapContent') // 高度由子组件撑开
5. 滚动处理超出内容
当内容超过容器高度时,嵌套 Scroll 组件实现滚动:
Scroll() {
RelativeContainer() {
// 多个子组件...
}
.height(800) // 内容高度超过父容器时滚动
}
.scrollable(ScrollDirection.Vertical)
.height('100%') // 滚动容器占满父高度
6. 动态高度调整
结合状态变量动态控制高度:
@State containerHeight: number = 300;
build() {
RelativeContainer() {
// 子组件...
}
.height(this.containerHeight) // 绑定动态高度
.onClick(() => {
this.containerHeight = 500; // 点击后调整高度
})
}
关键提示
单位使用:推荐使用 vp(虚拟像素)保证不同屏幕密度下的适配。
层级关系:确保 RelativeContainer 的父容器有明确高度,百分比高度才能生效。
性能优化:避免在 RelativeContainer 中嵌套过多复杂子组件,影响渲染效率。