React Native - Device back button handling

后端 未结 9 2102
感情败类
感情败类 2020-12-02 18:33

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.

9条回答
  •  抹茶落季
    2020-12-02 19:04

    This example will show you back navigation which is expected generally in most of the flows. You will have to add following code to every screen depending on expected behavior. There are 2 cases: 1. If there are more than 1 screen on stack, device back button will show previous screen. 2. If there is only 1 screen on stack, device back button will exit app.

    Case 1: Show previous screen

    import { BackHandler } from 'react-native';
    
    constructor(props) {
        super(props)
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
    }
    
    componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
    }
    
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
    }
    
    handleBackButtonClick() {
        this.props.navigation.goBack(null);
        return true;
    }
    

    Important: Don't forget to bind method in constructor and to remove listener in componentWillUnmount.

    Case 2: Exit App

    In this case, no need to handle anything on that screen where you want to exit app.

    Important: This should be only screen on stack.

提交回复
热议问题