HarmonyOS鸿蒙Next中父组件怎么修改子组件设置百分百的宽度变为自适应
HarmonyOS鸿蒙Next中父组件怎么修改子组件设置百分百的宽度变为自适应
子组件为公共组件,宽度设置百分百。父组件引用该子组件,怎么将子组件的宽度改为自适应?
import { HMRouter } from "@hadss/hmrouter";
@HMRouter({ pageUrl: '/demo' })
@Component
export struct demo {
build() {
Column() {
Column()
.width(13)
.height(13)
.margin({right: 4})
.backgroundColor(Color.Red)
// 调整子组件宽度自适应,不超出父组件宽度把右侧组件挤出去
demo2()
Column()
.width(13)
.height(13)
.backgroundColor(Color.Blue)
}
.padding(5)
.margin({top: 50})
.backgroundColor('#ff726262')
.width(150)
}
}
// 该组件为公共组件,宽度设置百分百
@Component
struct demo2{
build() {
// 宽度不调整
Text('一句“人生乐在相知心”镌刻着中拉论坛成立10年来')
.fontSize(12)
.fontWeight(500)
.fontColor('#fff')
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.ellipsisMode(EllipsisMode.END)
.width('100%')
}
}
更多关于HarmonyOS鸿蒙Next中父组件怎么修改子组件设置百分百的宽度变为自适应的实战教程也可以访问 https://www.itying.com/category-93-b0.html
通过布局权重分配:通过.layoutWeight(1)让子组件占据Row剩余空间,当空间不足时优先触发该组件的压缩换行。
在子组件中添加
.layoutWeight(1)
具体代码如下:
@Entry
@Component
export struct demo {
build() {
Row() {
Row()
.width(13)
.height(13)
.margin({right: 4})
.backgroundColor(Color.Red)
// 调整子组件宽度自适应,不超出父组件宽度把右侧组件挤出去
demo2()
Row()
.width(13)
.height(13)
.backgroundColor(Color.Blue)
}
.padding(5)
.margin({top: 50})
.backgroundColor('#ff726262')
.width(150)
}
}
// 该组件为公共组件,宽度设置百分百
@Component
struct demo2{
build() {
// 宽度不调整
Text('一句“人生乐在相知心”镌刻着中拉论坛成立10年来')
.fontSize(12)
.fontWeight(500)
.fontColor('#fff')
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.ellipsisMode(EllipsisMode.END)
.width('100%')
.layoutWeight(1)
}
}
更多关于HarmonyOS鸿蒙Next中父组件怎么修改子组件设置百分百的宽度变为自适应的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS NEXT中,要实现父组件修改子组件从100%宽度变为自适应,可以通过以下方式实现:
-
使用ArkUI的约束布局特性
子组件设置width: 'auto'
或移除width属性即可实现自适应宽度。父组件可通过Flex
、Row
或Column
容器控制布局。 -
使用自定义组件传参
父组件通过[@State](/user/State)
变量控制子组件的宽度属性:[@State](/user/State) childWidth: string = '100%' // 修改为 this.childWidth = 'auto'
-
响应式布局
利用onAreaChange
回调监听组件区域变化,动态调整子组件尺寸。
在HarmonyOS Next中,要让子组件从固定百分比宽度改为自适应宽度,可以通过以下几种方式实现:
- 最直接的方法是修改子组件demo2的宽度设置,将width(‘100%’)改为width(‘auto’):
Text('一句"人生乐在相知心"镌刻着中拉论坛成立10年来')
.width('auto') // 改为自适应
// 其他样式保持不变...
- 如果无法直接修改子组件代码,可以在父组件中通过布局约束覆盖子组件的宽度设置:
demo2()
.width('auto') // 在父组件中覆盖子组件的宽度设置
- 另一种方法是使用Flex布局,让父容器自动分配空间:
Row() { // 改为Row容器
Column()
.width(13)
.height(13)
.margin({right: 4})
.backgroundColor(Color.Red)
demo2()
.flexShrink(1) // 允许收缩
Column()
.width(13)
.height(13)
.backgroundColor(Color.Blue)
}
.width(150)
注意:当使用自适应宽度时,要确保文本不会溢出,可以配合maxLines和textOverflow属性控制文本显示。