【问题标题】:How to create global android device back button handler using React Native?如何使用 React Native 创建全局 android 设备后退按钮处理程序?
【发布时间】:2020-08-22 14:47:37
【问题描述】:

在我的场景中,我正在尝试为 android 后退按钮处理程序创建全局类,并在多个屏幕类文件中重用它。怎么做?我尝试了下面的代码,但我不知道如何从其他类访问公共类。

我的代码如下 (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 ios typescript react-native


    【解决方案1】:

    下面的代码可以在你想用android的后退按钮返回时显示一个警报,你需要使用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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2019-05-14
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      相关资源
      最近更新 更多