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.

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

@oijafoijf asnjksdjn Please accept the answer if it helps you, thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.