React Native
[React-Native] 뒤로가기 구현 ( BackHandler )
sayhee
2023. 3. 20. 16:50
728x90
Home에서 뒤로가기를 눌렀을 경우 앱을 종료할 수 있도록 BackHandler을 통해 구현해보았습니다.
✅ 안드로이드에서 뒤로가기 버튼을 사용하기 위해 BackHandler를 import
import { BackHandler } from 'react-native';
✅ 이벤트 리스너가 필요한 부분에 구현
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.backPressed);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.backPressed);
}
BackHandler.addEventListener : 이벤트 리스너를 생성하고
BackHandler.removeEventListener : 지워야 하는 객체를 반환합니다
✅ 컴포넌트 코드 내에 위에서 선언한 backPressed 함수 추가
//뒤로가기 했을 때 앱 종료
backPressed = () => {
Alert.alert(
'',
'앱을 종료하시겠습니까?',
[
{ text: '취소', onPress: () => console.log('Cancel Pressed'), style: 'cancel' },
{ text: '확인', onPress: () => BackHandler.exitApp() },
],
{ cancelable: false });
return true;
}
- return false : 뒤로가기 명령 실행
- return true : 뒤로가기 명령 무시
* 모달이 팝업이 되어있는 상태에서 BackHandler을 사용하려고 했는데 작동이 되지 않았다.
( 비밀번호 확인창 : Modal로 구현함 )
✅ Modal의 onRequestClose document
- react-native document에서 modal의 onRequestClose에 대해 확인해보니
모달이 열려있을 때는 BackHandler 이벤트가 발생되지 않는다고 한다
✅ Modal에서 뒤로가기 구현
<Modal
onRequestClose={()=>this.props.navigation.pop()}
transparent={false}
visible={this.state.modal}
>
</Modal>
Modal에서는 onRequestClose 함수를 사용하여 뒤로가기 구현을 할 수 있다.