在onTouchDown方法中改变状态变量的值后无法引起UI刷新,代码和运行效果如下:
@Component
struct ContainerView {
@BuilderParam child: () => void
onTouchDown = () => {
}
onTouchUp = () => {
}
build() {
Column() {
Button('长按按钮')
.onTouch((event) => {
if (event.type === TouchType.Down) {
this.onTouchDown()
} else if (event.type === TouchType.Up) {
this.onTouchUp()
}
})
this.child()
}
}
}
@Entry
@Component
struct MainPage {
@State title: string = '未点击'
build() {
Column() {
ContainerView(
{
onTouchDown: this.onTouchDown,
onTouchUp: () => {
this.title = 'onTouchUp'
}
}
) {
Text(this.title)
.fontSize(20)
}
}
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
onTouchDown() {
this.title = 'onTouchDown'
}
} 
修改onTouchDown函数,具体代码和运行效果如下:
@Component
struct ContainerView {
@BuilderParam child: () => void;
// 实际调用的onTouchDown方法
onTouchDown = () => {
};
onTouchUp = () => {
};
build() {
Column() {
Button('长按按钮')
.onTouch((event) => {
if (event.type === TouchType.Down) {
this.onTouchDown();
} else if (event.type === TouchType.Up) {
this.onTouchUp();
}
});
this.child();
};
}
}
@Entry
@Component
struct TouchDownCustom {
@State title: string = '未点击';
build() {
Column() {
ContainerView(
{
// 修改后的代码
onTouchDown: (): void => this.onTouchDown(),
onTouchUp: () => {
this.title = 'onTouchUp';
}
}
) {
Text(this.title)
.fontSize(20);
};
}
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center);
}
onTouchDown() {
this.title = 'onTouchDown';
}
} 