简体   繁体   English

React-Native 与 Expo:手柄硬件返回按钮

[英]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.

相关问题 如何阻止Android硬件后退按钮在react-native的react-navigation中运行? - How to stop the Android Hardware Back Button from functioning in react-navigation for react-native? 使用纯JavaScript将React-Native(Expo)应用发送到Android后退按钮按下的背景吗? - Send a React-Native (Expo) app to the background on Android back button press with pure JavaScript? React-Native BackHandler始终在Android中关闭App(硬件返回) - React-Native BackHandler always closes App in Android (hardware back) react-native:后退按钮处理程序 - react-native: back button handler 当在 react-native 中按下硬件后退按钮时,无法对同一组件执行 2 个操作,以下是有关反处理程序的代码 - Not able to perform 2 actions on the same component when hardware back button is pressed in react-native,below are the code regarding the backhandler React-native Expo 语音选项 - React-native Expo SpeechOptions 处理硬件后退按钮 - Handle hardware back button click 如何在 React-navigation/react-native 中隐藏后退按钮 - how to hide back button in React-navigation/react-native 使用Android硬件导航时出现导航问题Back Press [react-native] - Navigation Issue while navigating using Android Hardware Back Press [react-native] React-Native:后退按钮设置保留在所有组件上 - React-Native: Back button settings stays on all components
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM