0

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.

oijafoijf asnjksdjn
  • 1,115
  • 12
  • 35

1 Answers1

2

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
}
Tommy Leong
  • 2,509
  • 6
  • 30
  • 54