HarmonyOS鸿蒙Next中快应用学习之页面周期函数onBackPress无法触发?
HarmonyOS鸿蒙Next中快应用学习之页面周期函数onBackPress无法触发? 【关键词】
onBackPress、退出提示
【问题背景】
在学习和调试快应用的过程中,我在子页面中的onBackPress()函数中定制了退出的一个弹框提醒,将它作为组件引入父页面中,弹框却无法触发?
问题代码如下:
子页面
import shortcut from '@system.shortcut';
import prompt from '@system.prompt';
import router from '@system.router'
module.exports = {
onInit: function() {
this.$page.setTitleBar({
text: '创建桌面图标',
backgroundColor: '#007DFF',
backgroundOpacity: 0.5,
});
},
setShortcut() {
shortcut.install({
message: 'Adds the shortcut to the desktop for convenient use next time.',
success: function(ret) {
console.log('handling createShortCut success');
},
fail: function(erromsg, errocode) {
prompt.showToast({
message: erromsg + errocode,
duration: 2000,
gravity: 'bottom'
})
}
});
},
hasinstallShortcut() {
shortcut.hasInstalled({
success: function(ret) {
console.log('hasInstalled success ret---' + ret);
if (ret) {
prompt.showToast({
message: 'has'
})
} else {
prompt.showToast({
message: 'has not'
})
}
}.bind(this),
fail: function(erromsg, errocode) {
console.log('hasInstalled fail ret---' + erromsg);
}.bind(this),
complete: function() {}
});
},
deeplink() {
router.push({
uri: 'hap://app/com.yzhj.yicaiyipu'
});
},
click(event) {
console.log(event, event.eventStatusCode);
prompt.showToast({
message: event.eventMessage
});
},
turnTo() {
router.push({
uri: `/homePage?package='com.huawei.QuickAppDemo'`
});
},
onBackPress() {
console.log("back!!");
var that = this;
shortcut.install({
message: '我看你很喜欢这个应用呢,加个桌面再退出吧',
success: function(ret) {
console.log('添加成功');
that.$app.exit()
},
fail: function(erromsg, errocode) {
prompt.showToast({
message: erromsg + errocode,
duration: 2000,
gravity: 'bottom'
})
}
})
return true
},
}
父页面
import shortcut from '@system.shortcut';
import prompt from '@system.prompt';
module.exports = {
data: {
componentData: {
message: '点击跳转快应用',
},
},
onInit() {
this.$page.setTitleBar({
text: '欢迎来到快应用',
textColor: '#ffffff',
backgroundColor: '#007DFF',
backgroundOpacity: 0.5,
menu: true
});
},
}
控制台输出如下:
没有打印"back!!"。
【问题分析】
这是方法调用返回值不正确或者使用位置不对导致的。根据华为开发者官网里面对快应用页面生命周期函数以及相关案例的介绍:
开发者若想重写onBackPress生命周期,在里面自定义返回逻辑,返回值必须为true,否则快应用引擎会按照false处理,页面直接退出。且作为子组件引入时,onBackPress方法不能写在子组件中,得写在父组件中才行。
【解决方法】
确保返回值为true,把子组件里面的onBackPress方法移动到父组件中来,这个问题就可以解决了。
打印内容出现,且出现弹窗。
更多关于HarmonyOS鸿蒙Next中快应用学习之页面周期函数onBackPress无法触发?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS鸿蒙Next中快应用学习之页面周期函数onBackPress无法触发?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,快应用的onBackPress
页面周期函数无法触发,可能是由于以下原因:
- 页面栈管理问题:确保当前页面处于栈顶,
onBackPress
仅在用户按下返回键且页面为栈顶时触发。 - 生命周期未正确注册:检查页面生命周期函数是否正确注册,确保
onBackPress
在页面配置中已声明。 - 系统版本兼容性:确认使用的鸿蒙系统版本支持
onBackPress
,某些旧版本可能不支持该函数。 - 事件冲突:检查是否有其他事件或逻辑阻止了
onBackPress
的触发。
建议检查上述问题,确保页面生命周期函数正确配置。