React Native 之 AppState(应用状态)(二十二)

import React, { useEffect } from 'react'; import { AppState, Text, View, StyleSheet } from 'react-native'; const AppStateExample = () => { const handleAppStateChange = (nextAppState) => { if (nextAppState === 'active') { console.log('App has come to the foreground!'); } else if (nextAppState === 'background') { console.log('App has gone to the background!'); } else if (nextAppState === 'inactive') { console.log('App is in an inactive state!'); } }; useEffect(() => { const subscription = AppState.addEventListener('change', handleAppStateChange); // 清理函数,确保在组件卸载时移除监听器 return () => { subscription.remove(); }; }, []); // 空依赖数组确保 effect 只在组件挂载和卸载时运行 return ( <View style={styles.container}> <Text>Open the app switcher (double tap home button) and check the console to see the logs.</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default AppStateExample;
上一篇:类和对象(上)


下一篇:React Native 之 react-native-share(分享)库 (二十三)