[英]How to implement callBack function when screen change in react-native?
更改屏幕执行时我需要一个函数,我的意思是当从屏幕主页导航到执行回调函数的关于屏幕时。
我想在更改任何 naviagte run 回调函数以进行某些检查时创建全局堆栈,例如( userToken、internet 状态、检查位置是 1 或关闭等)
我为堆栈导航和实现UNSAFE_componentWillUpdate
创建了一个类组件,可以检测到任何导航。
代码
UNSAFE_componentWillUpdate(prevProp, prevState) {
if (prevProp != this.props) {
console.log('change state navigation');
}
}
index-zero
主屏幕。<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
/>
<Stack.Screen
name="About"
component={About}
/>
</Stack.Navigator>
您可以使用“NavigationContainer”中的“onNavigationStateChange”道具获取当前路线
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = this.getCurrentRouteName(currentState);
const prevScreen = this.getCurrentRouteName(prevState);
}}
// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route);
}
return route.routeName;
}
<NavigationContainer
ref={navigationRef}
onReady={() => routeNameRef.current = navigationRef.current.getCurrentRoute().name}
onStateChange={() => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name
if (previousRouteName !== currentRouteName) {
// The line below uses the expo-firebase-analytics tracker
// https://docs.expo.io/versions/latest/sdk/firebase-analytics/
// Change this line to use another Mobile analytics SDK
Analytics.setCurrentScreen(currentRouteName);
}
// Save the current route name for later comparision
routeNameRef.current = currentRouteName;
}}
>
{/* ... */}
</NavigationContainer>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.