美文网首页
RN:自定义安卓BackHandler的相应逻辑

RN:自定义安卓BackHandler的相应逻辑

作者: 春暖花已开 | 来源:发表于2023-04-02 09:26 被阅读0次

    为了更好的用户体验,建议使用react-native-exit-appexitApp 来替代 BackHandler的。

    import { useFocusEffect } from '@react-navigation/native'
    import { useCallback, useRef } from 'react'
    import { BackHandler } from 'react-native'
    import ExitApp from 'react-native-exit-app'
    import { ToastAtCenter } from '~/components/Toast'
    
    function useRootBackBehavior() {
      const lastTime = useRef()
    
      useFocusEffect(
        useCallback(() => {
          const onBackPress = () => {
            if (lastTime.current && lastTime.current + 2000 >= new Date().getTime()) {
              ExitApp.exitApp()
              return true
            } else {
              lastTime.current = new Date().getTime()
              ToastAtCenter('再按一次退出应用')
              return true
            }
          }
    
          const subscription = BackHandler.addEventListener('hardwareBackPress', onBackPress)
          return () => subscription.remove()
        }, [])
      )
    }
    
    export default useRootBackBehavior
    

    相关文章

      网友评论

          本文标题:RN:自定义安卓BackHandler的相应逻辑

          本文链接:https://www.haomeiwen.com/subject/cwoqddtx.html