我正在将 Ionic 与 React 结合使用来开发应用程序。我找不到有关如何处理硬件后退按钮单击以及如何退出应用程序的任何文档。是否有任何有关此的文档或教程?
答案 0 :(得分:5)
import React, { useEffect } from "react";
import { Plugins, Capacitor } from "@capacitor/core";
useEffect(() => {
if (Capacitor.isNative) {
Plugins.App.addListener("backButton", (e) => {
if (window.location.pathname === "/") {
// Show A Confirm Box For User to exit app or not
let ans = window.confirm("Are you sure");
if (ans) {
Plugins.App.exitApp();
}
} else if (window.location.pathname === "/YourFirstPageRoute") {
// Show A Confirm Box For User to exit app or not
let ans = window.confirm("Are you sure");
if (ans) {
Plugins.App.exitApp();
}
}
});
}
}, []);
答案 1 :(得分:1)
要在硬件上单击“后退”按钮后退出应用程序,首先必须防止返回默认历史记录。 https://ionicframework.com/docs/react/config
// App component
import { setupConfig } from '@ionic/react'
setupConfig({
hardwareBackButton: false
})
然后添加监听器后退按钮
https://capacitor.ionicframework.com/docs/apis/app#method-addListener-3
import { Plugins, Capacitor } from '@capacitor/core'
...
useEffect(() => {
if (Capacitor.isNative) {
Plugins.App.addListener('backButton', e => {
// Use of location.pathname is also correct
if (window.location.pathname === '/') {
Plugins.App.exitApp()
} else if (window.location.pathname === '/detail') {
history.push('/')
} else {
history.back()
}
})
}
}, []) // eslint-disable-line
...
答案 2 :(得分:0)
好吧,您可以在退出主页/主页/仪表板页面之前发出确认警报。 我添加了带有2个按钮的IonAlert。 请在下面的实际设备中查看我的工作代码:
import React, {useState } from 'react';
import { IonAlert } from '@ionic/react';
import { Plugins } from "@capacitor/core";
const HomePage: React.FC = () => {
const { App } = Plugins;
const [showBackAlert, setShowBackAlert] = useState(false);
// listening to ionic back button event
document.addEventListener('ionBackButton', (ev: any) => {
ev.detail.register(-1, () => {
// when you are in your home(last) page
if (history.location.pathname === '/home') {
// calling alert box
setShowBackAlert(true);
}
});
});
return (
<IonPage>
<IonAlert
isOpen={showBackAlert}
header={'Please Confirm!'}
message={'Do you really want to exit our App?'}
buttons={[
{
text: 'Nope',
role: 'cancel',
cssClass: 'secondary',
handler: () => {}
},
{
text: 'Yeah',
handler: () => {
App.exitApp();
}
}
]}
onDidDismiss={() => setShowBackAlert(false)}
cssClass='my-custom-class'
/>
</IonPage >
);
};
export default HomePage;