问题1:100%宽度右边超出范围解决方式
使用Row宽度设置100%,当前Row设置外边距或父组件设置外边距或内边距导致右边内容超出范围。
解决方式:使用Text.layoutWeight(1)占据Row里面剩余全部空间
问题2:横向布局左边高度跟随右边高度撑开
方式:动态高度计算(精准控制)
若右侧内容高度动态变化需精准同步到左侧,可以通过 自定义回调 或 弹性盒子监听 动态设置左侧组件高度。参考以下思路:
@Entry
@Component
struct DynamicHeightExample {
@State rightHeight: number = 0 // 绑定右侧组件高度
build() {
Row() {
// 左侧组件:高度绑定 rightHeight
Column() {
Text('左侧内容')
}
.backgroundColor('#FF0000')
.height(this.rightHeight) // 动态绑定高度
// 右侧组件:渲染完成后更新 rightHeight
Column() {
Text('右侧动态高度内容,右侧动态高度内容,右侧动态高度内容,右侧动态高度内容')
}
.backgroundColor('#0000FF')
.padding(10)
.onAreaChange((oldArea, newArea) => {
this.rightHeight = newArea.height // 监听区域变化,更新左侧高度
})
}
.width('100%')
}
}
问题3:在方法如何像自带组件那样使用{}传参,不用按顺序传入
可以像 TextOptions 这样把方法里面的入参封装到interface或class里面
参考思路:
interface TextOptions {
controller: TextController;// 未加问号一定要传的参数
text?: string;// 加问号非必传的参数
}
问题4:HashMap不能直接使用中括号[],map['key']不能获取和设置值,运行时会报错
Error message:Cannot set property on Container
原因分析
- 与原生对象的机制不同
对象字面量({}):键会被转换为字符串,且属性直接挂在对象实例上,可通过obj[key]访问。
Map类:内部通过get/set方法维护一个真正泛型的键值存储,键可以是任意类型(如对象),不会被转换为字符串属性。 - 类型安全的强制要求
Map提供严格的泛型约束(如Map<string, number>),方法调用可确保类型的正确性。
若允许map[key]形式,会绕过TypeScript的类型检查,增加潜在错误风险。
使用方式:
在ArkTS(或TypeScript)中,Map类型不直接支持方括号语法(如map['key'])访问键值,而必须通过.get(key)和.set(key, value)方法
问题5:自定义弹窗如何解耦,脱离页面@Component去使用
实现方式:可以抽离 @CustomDialog ,手动 new 一个 Component 组件,在组件里面去实现弹窗逻辑,
@Component
export struct DialogView {
showDialog(): CustomDialogController {
let dialogController = new CustomDialogController({
builder: CustomDialog(),
autoCancel: true,
alignment: DialogAlignment.Center,
offset: { dx: 0, dy: -20 },
customStyle: false,
backgroundColor: 0xd9ffffff,
cornerRadius: 10,
gridCount: 6
})
return dialogController
}
build() {
}
}
@Component
export struct Index {
dialog = new DialogView()
build() {
Text('显示对话框').onClick(()=>{
dialog.showDialog()
})
}
}
还可以用promptAction.openCustomDialog,这个就能完全脱离了,直接静态方法就可以显示
import promptAction from '@ohos.promptAction'
let customDialogId: number = 0
@Builder
function customDialogBuilder(dialogTxt:string,index:string) {
TestDialog({ dialogTxt: dialogTxt,content:index })
}
@Component
struct TestDialog {
@State dialogTxt: string = ''
@State content: string = ''
build() {
Column() {
Text(this.dialogTxt+this.dialogTxt).fontSize(20)
Row() {
Button("确认").onClick(() => {
promptAction.closeCustomDialog(customDialogId)
})
Blank().width(50)
Button("取消").onClick(() => {
promptAction.closeCustomDialog(customDialogId)
})
}.margin({ top: 80 })
}.height(200).padding(5)
}
}
@Entry
@Component
struct Index {
@State message: string = '打开弹窗'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
promptAction.openCustomDialog({
builder: customDialogBuilder.bind(this, '标题','内容')// 重点,要把当前组件传进去
}).then((dialogId: number) => {
customDialogId = dialogId
})
})
}
.width('100%')
}
.height('100%')
}
}
问题5:弹窗(Dialog)如何完全设置背景色透明
自定义弹窗(Dialog、CustomDialog)设置了背景色透明(backgroundColor: Color.Transparent),但是发现还有一层淡淡的蒙版。
解决方式:
// promptAction.openCustomDialog 弹窗方式
backgroundColor: Color.Transparent // 背景透明
maskColor: Color.Transparent // 蒙版透明,关键
// 或着
backgroundColor: Color.Transparent // 背景透明
isModal: false // 模态窗口有蒙层,非模态窗口无蒙层
// CustomDialogController 弹窗方式
backgroundColor: Color.Transparent // 背景透明
maskColor: Color.Transparent // 蒙版透明,关键
customStyle: true, // 启用自定义样式(避免系统默认约束),关键
// 或着
backgroundColor: Color.Transparent // 背景透明
isModal: false // 模态窗口有蒙层,非模态窗口无蒙层
customStyle: true, // 启用自定义样式(避免系统默认约束),关键
问题6:组件高度自适应,如何限制最大高度
方式:使用constraintSize方法可以设置约束尺寸,组件布局时,进行尺寸范围限制。这里设置Scroll组件的高度限制。
Scroll() {
Column() {
if (this.wrapBuilder) {
// 创建自定义视图
this.wrapBuilder.builder()
}
}.width('100%')
}.width('100%')
.constraintSize({maxHeight: 300})// 重点
问题7:Tabs根据官网示例做了指示器动画,慢慢滑动会导致指示器先切换到目标在切回原来的tab
Tabs-导航与切换-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者
.onGestureSwipe((index: number, event: TabsAnimationEvent) => {
// 在页面跟手滑动过程中,逐帧触发该回调。
if (this.isSwitchTab) {
this.startAnimateTo(this.animationDuration, this.textInfos[this.curIndex][0], this.textInfos[this.curIndex][1])
return // tab已经切换停止
}
let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
this.currentIndex = currentIndicatorInfo.index
this.setIndicatorAttr(currentIndicatorInfo.left, currentIndicatorInfo.width)
})
isSwitchTab:boolean = false// 是否全换tab
private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
let nextIndex = index
if (index > 0 && event.currentOffset > 0)) {
nextIndex--
} else if (index < this.textInfos.length - 1 && event.currentOffset < 0)) {
nextIndex++
}
let indexInfo = this.textInfos[index]
let nextIndexInfo = this.textInfos[nextIndex]
let swipeRatio = Math.abs(event.currentOffset / this.tabsWidth)
let currentIndex = swipeRatio > 0.5 ? nextIndex : index // 页面滑动超过一半,tabBar切换到下一页。
isSwitchTab = true
let currentLeft = indexInfo[0] + (nextIndexInfo[0] - indexInfo[0]) * swipeRatio
let currentWidth = indexInfo[1] + (nextIndexInfo[1] - indexInfo[1]) * swipeRatio
return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth }
}
// 组件顶层监听触摸事件
.onTouch((event: TouchEvent) => {
if (event.type == TouchType.Up || event.type == TouchType.Cancel) {
this.isSwitchTab = false
}
})
问题8:ForEach、LazyForEach数据已刷新UI未更新问题
解决方式:手动设置keyGenerator内容,把会变动的值拼接成字符串返回,如下面源码
注意:keyGenerator直接吧真个对象转json使用的话会导致页面卡顿
ForEach(this.vm.timeWatchList, (item: TestBean) => {
ListItem() {
TestCard({ timeWatch: item })
}
}, (item: TestBean, index: number) => item.value + '_' + index)
问题9:@Builder方法数据已刷新UI未更新问题
原因:@Builder存在两个或者两个以上参数,就算通过对象字面量的形式传递,值的改变也不会引起UI刷新。
@Builder只接受一个参数,当传入一个参数的时候,通过对象字面量的形式传递,值的改变会引起UI的刷新。
// 未解决更新UI方式
this.tabText(0, `全部(${this.count})`)
@Builder
tabText(index: number, name: string) {
Text(name)
}
// 解决更新UI方式
this.tabText(0, `全部`)
@Builder
tabText(index: number, name: string) {
Text(`${this.name}(${this.count})`)
}
问题10:V2状态管理,自定义组件数据已经刷新UI未更新问题
原因:接口返回的数据是JsonObject并不是真正我们想要的对象,然后里面就没有对应注解,就会导致更新JsonObject里面的字段,对应UI不更新
解决方式:
- 自己创建一个就想要对象,再赋值
- 使用第三方SDK把JsonObject转成想要的对象,如:class-transformer
具体可以参考下面代码
import { JSON } from "@kit.ArkTS"
import { plainToInstance } from "class-transformer"
@ObservedV2
class TestBean {
@Trace test2: TestBean2 = new TestBean2()
}
@ObservedV2
class TestBean2 {
@Trace num: number = 0
}
@ComponentV2
export struct TestComponent {
test: TestBean = new TestBean()
build() {
Column() {
Button('new创建新对象-更新UI').onClick(() => {
// new出来TestBean2,所以更新UI
this.test.test2 = new TestBean2()
}).margin({ top: 100 })
Button('模拟接口创建新对象-不更新UI').onClick(() => {
// 其实还是个JsonObject对象,未真正转成TestBean2,所以不更新UI
this.test.test2 = JSON.parse('{"num":-1}') as TestBean2
}).margin({ top: 10 })
Button('模拟接口创建新对象-更新UI').onClick(() => {
// 真正转成TestBean2,所以更新UI
let test2 = plainToInstance(TestBean2,JSON.parse('{"num":-1}'))
this.test.test2 = test2
}).margin({ top: 10 })
Button('累加').onClick(() => {
this.test.test2.num++
}).margin({ top: 10 })
TestComponent2({ test2: this.test.test2, num: this.test.test2.num }).margin({ top: 10 })
}
.size({ width: '100%', height: '100%' })
}
}
@ComponentV2
export struct TestComponent2 {
@Param @Require test2: TestBean2
@Param num: number = 0
build() {
Column() {
Text(`测试:${this.num}`).margin({ top: 10 })
}
.size({ width: '100%', height: '100%' })
}
}