美文网首页React Native
React Native 再按一次退出

React Native 再按一次退出

作者: 本间麻衣子 | 来源:发表于2018-01-11 22:46 被阅读0次

好东西当然要分享,代码一起用
我们使用 React Native 提供的 API BackHandler

监听设备上的后退按钮事件。
Android:监听后退按钮事件。如果没有添加任何监听函数,或者所有的监听函数都返回false,则会执行默认行为,退出应用。


Methods

exitApp()

static exitApp()

addEventListener()

static addEventListener(eventName, handler)

removeEventListener()

static removeEventListener(eventName, handler)

Code

当组件卸载时一定要移除 hardwareBackPress 监听事件

... 
componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid)
}

lastBackPressed = 0
onBackAndroid = () => {
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        BackHandler.exitApp()
        return false
    }
    this.lastBackPressed = Date.now()
    ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT)
    return true
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid)
}
...

相关文章

网友评论

    本文标题:React Native 再按一次退出

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