HarmonyOS 鸿蒙Next手势抽离问题
HarmonyOS 鸿蒙Next手势抽离问题
在鸿蒙开发中,对于大量的组合手势操作。我想要将其抽离出来成一个属性值。但是我发现当我抽离出来的时候,app编译失败,报错为
Error message:Cannot read property onActionStart of undefined。
个人猜测原因是因为手势实例时需要一定的UI 环境
代码如下
@Entry
@ComponentV2
struct Index {
@Local offsetX: number = 0
@Local offsetY: number = 0
@Local positionX: number = 0
@Local positionY: number = 0
private myGesture: GestureType = PanGesture()
.onActionStart((event: GestureEvent | undefined) => {
console.log(“dubug”)
})
.onActionUpdate((event: GestureEvent | undefined) => {
if (event) {
console.info(“触发,offsetX:”,this.offsetX,“offsetY:”,this.offsetY)
this.offsetX = this.positionX + event.offsetX
this.offsetY = this.positionY + event.offsetY
}
})
.onActionEnd((event: GestureEvent | undefined) => {
console.log(“结束”)
this.positionX = this.offsetX
this.positionY = this.offsetY
})
build() {
Column() {
Row() {
Image($r(‘app.media.avatar’))
.translate({
x: this.offsetX,
y: this.offsetY
})
.gesture(this.myGesture)
}
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
因此我将其封装成了一个回调函数,并在获取手势参数时运行回调函数获取手势
代码逻辑大致如下:
@Entry
@ComponentV2
struct Index {
@Local offsetX: number = 0
@Local offsetY: number = 0
@Local positionX: number = 0
@Local positionY: number = 0
private myGesture: ()=>GestureType = ()=>PanGesture()
.onActionStart((event: GestureEvent | undefined) => {
console.log(“dubug”)
})
.onActionUpdate((event: GestureEvent | undefined) => {
if (event) {
console.info(“触发,offsetX:”,this.offsetX,“offsetY:”,this.offsetY)
this.offsetX = this.positionX + event.offsetX
this.offsetY = this.positionY + event.offsetY
}
})
.onActionEnd((event: GestureEvent | undefined) => {
console.log(“结束”)
this.positionX = this.offsetX
this.positionY = this.offsetY
})
build() {
Column() {
Row() {
Image($r(‘app.media.avatar’))
.translate({
x: this.offsetX,
y: this.offsetY
})
.gesture(this.myGesture())
}
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
编译能够成功,但效果不生效。我已确认我的手势设置没有问题,但很疑惑鸿蒙在这一块的封装逻辑
关于HarmonyOS 鸿蒙Next手势抽离问题的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
UI范式代码要么在build方法体,要么是有[@Builder](/user/Builder)修饰的方法,上述写法不会将GestureGroup代码识别为UI范式。