React Native 之 AppState(应用状态)
import React, { useEffect, useState } from 'react';
import { AppState, Text, View } from 'react-native';
const AppStateExample = () => {
const [appState, setAppState] = useState(AppState.currentState);
// 组件挂载后注册监听器
useEffect(() => {
AppState.addEventListener('change', _handleAppStateChange);
// 组件卸载前移除监听器
return () => {
AppState.removeEventListener('change', _handleAppStateChange);
};
}, []);
// 处理应用状态变化的函数
const _handleAppStateChange = (nextAppState) => {
if (appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
}
setAppState(nextAppState);
};
return (
<View>
<Text>Current app state is: {appState}</Text>
</View>
);
};
export default AppStateExample;
这段代码使用React Native的AppState API来监听应用的状态变化。当应用从后台变为前台时,它会在控制台输出一条消息。这是一个很好的学习示例,展示了如何在React Native应用中使用AppState。
评论已关闭