簡體   English   中英

如何使用 React Native 創建全局 android 設備后退按鈕處理程序?

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

在我的場景中,我正在嘗試為 android 后退按鈕處理程序創建全局 class 並在多個屏幕 class 文件中重用它。 怎么做? 我嘗試了下面的代碼,但我不知道如何從其他類訪問常見的 class。

下面是我的代碼 (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;
      }
    }
}

當您想使用 android 后退按鈕返回 go 時,以下代碼允許顯示警報,您需要使用 react native BackHandler組件,如下所示。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM