简体   繁体   中英

How to create global android device back button handler using React Native?

In my scenario, I am trying to create global class for android back button handler and reuse it in multiple screen class files. How to do it? I tried below code but I dont know how to access common class from other classes.

My Code Below (Androidhandler.tsx)

export default class hardware extends Component {
  constructor(props) {
    super(props);
    this.BackButton = this.BackButton.bind(this);
  }

  componentWillMount() {
    BackHandler.addEventListener'BackPress',this.BackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('BackPress',this.BackButton);
  }

  BackButton() {
    if(this.props.navigation){
        this.props.navigation.goBack(null);
        return true;
      }
    }
}

the following code allows to show an alert when you want to go back with the android back button, what you need is to use the react native BackHandler component as follows.

import { BackHandler } from "react-native"

export default class hardware extends Component {
  constructor(props) {
    super(props);
    this.BackButton = this.BackButton.bind(this);
  }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.BackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', () => {
      if (this.props.navigator && this.props.navigator.getCurrentRoutes().length > 1) {
        this.navigator.pop();
        return true;
      }
      return false;
    });
  }

  BackButton() {
    Alert.alert(
      'Warning',
      'Are you sure to leave?',
      [
        {
          text: 'Cancel',
          style: 'cancel'
        },
        { text: 'OK', onPress: () => BackHandler.exitApp() }
      ],
    );
    return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM