[英]React-Native with Expo: Handle Hardware Back Button
By following these directions I managed to make the back button force my WebView to navigate back to the last page.按照这些指示,我设法使后退按钮强制我的 WebView 导航回最后一页。
However I'm facing a side-effect: besides going back on the navigation, it also exits the App, in Android.但是我面临一个副作用:除了返回导航之外,它还退出应用程序,在 Android 中。 Below is my current code.
以下是我当前的代码。 Does anyone know what is wrong with it?
有谁知道它有什么问题?
function useBackButton(handler: any) {
useEffect(()=> {
BackHandler.addEventListener("hardwareBackPress", handler)
return () => {
BackHandler.removeEventListener("hardwareBackPress", handler)
}
}, [handler])
}
export default function App() {
const webviewRef = useRef(null)
function backButtonHandler() : any {
console.log("==> Back Pressed", webviewRef.current)
if (webviewRef) {
if (webviewRef.current) {
webviewRef.current.goBack()
}
}
}
useBackButton(backButtonHandler)
return (
<WebView
source={{uri: "http://my-website"}}
style={{ marginTop: 40 }}
ref={webviewRef}
sharedCookiesEnabled
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
As indicated by @Nadia Chibrikova, indeed there was a "return true" missing:正如@Nadia Chibrikova 所指出的,确实缺少“返回真”:
function backButtonHandler() : any {
console.log("==> Back Pressed", webviewRef.current)
if (webviewRef) {
if (webviewRef.current) {
webviewRef.current.goBack()
}
}
return true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.