react-native 앱 종료 방법에 대해 포스팅 해보기로 한다.
react-native 앱 종료 방법은 2가지가 있다.
1. react-native에서 제공해주는 BackHandler를 사용하는 법
import React, {useEffect} from 'react';
import {Text, View, StyleSheet, BackHandler, Alert} from 'react-native';
const App = () => {
useEffect(() => {
const backAction = () => {
Alert.alert('Hold on!', 'Are you sure you want to go back?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{text: 'YES', onPress: () => BackHandler.exitApp()},
]);
return true;
};
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction,
);
return () => backHandler.remove();
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>Click Back button!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 18,
fontWeight: 'bold',
},
});
export default App;
주의해야할 점.
1. iOS는 적용이 안되고, Android에서만 작동한다.
2. 앱을 완전히 kill 하는 것이 아닌 백그라운드 상태로 보낸다.
2. react-native-exit-app 라이브러리
- iOS, Android에서 모두 작동한다.
- 앱을 백그라운드 상태가 아닌 완전히 kill 한다.
설치
npm install react-native-exit-app --save
react-native link react-native-exit-app
Native 코드 수정 - Android
- In the settings.gradle
include ':react-native-exit-app', ':app' project(':react-native-exit-app').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-exit-app/android')
- In the build.gradle
implementation project(':react-native-exit-app')
- In MainApplication.java
import com.github.wumke.RNExitApp.RNExitAppPackage; ... @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( ... new RNExitAppPackage(), ... ); } ...
사용법
import RNExitApp from 'react-native-exit-app';
...
RNExitApp.exitApp();
...
'React-Native' 카테고리의 다른 글
[react-native] 화면이 mount 될 때 DeviceEventEmitter 동작하기 (0) | 2023.03.22 |
---|---|
[React native] android 릴리즈 모드에서 network error (0) | 2023.02.24 |
[React-Native] 그라데이션 적용 (0) | 2022.12.30 |
[React-Native] useWindowDimensions 화면 크기 대응 (0) | 2022.12.27 |
React Hook - useState를 활용하여 탭 구성하기 (2) | 2022.12.24 |