React Native Android - how to disable android back button in StackNavigator

不羁的心 提交于 2019-12-11 18:19:34

问题


I am trying to implement a lock screen. Only when the password is correct does the screen go back, otherwise the screen must not be exited. But if you press the Back button on Android, it will always go back. I tried using BackHandler but it failed. It seems to be related to StackNavigator. How can I do nothing when the backButton is pressed?

import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PINCode from '@haskkor/react-native-pincode';
import { BackHandler } from 'react-native';
import {
  View, Text, Button,
} from 'native-base';
import { NavigationEvents } from 'react-navigation';
import Colors from '../common/Colors';

class LockScreenContainer extends PureComponent {
  static navigationOptions = () => ({
    header: false,
    gesturesEnabled: false,
  });

  finishProcess = async () => {
    const { navigation } = this.props;
    navigation.goBack();
  }

  render() {
    const { navigation,isLock } = this.props;

    return (
      <View style={{ backgroundColor: Colors.GRAY_LV0, justifyContent: 'center', flex: 1 }}>
        <NavigationEvents
          onWillBlur={() => BackHandler.removeEventListener('hardwareBackPress')}
          onWillFocus={() => BackHandler.addEventListener('hardwareBackPress', () => false)}
        />
        <PINCode
          status={isLock ? 'enter' : 'choose'}
          finishProcess={this.finishProcess}
        />
      </View>
    );
  }
}

export default connect(
  state => ({
    isLock: state.lock.isLock,
  }),
  undefined,
)(LockScreenContainer);

insert BackHandler.addEventListener ('hardwareBackPress', () => false) into componentDidMount also has the same result.


回答1:


You may do something like the following

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

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


backButtonActionCheck = () => {
// Your logic to check if user should go back or stay
}


来源:https://stackoverflow.com/questions/58333241/react-native-android-how-to-disable-android-back-button-in-stacknavigator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!