React native -如何在推送通知点击上导航?



我使用的是react-native-push-notification。当应用程序处于后台/已杀死状态时,我有通知未显示的问题,在多个论坛和GitHub中的解决方案是我们在index.js中初始化和配置推送通知(PushNotification.configure())在PushNotification.configure()函数中,onNotification()是单击推送通知时调用的函数。点击,我想导航到一个特定的屏幕在应用程序中,但这是不可能的,目前没有导航道具可用的index.js

有什么办法可以使导航成为可能吗?

您可以这样做。首先,您可以从NavigationContainer所在的文件中初始化并导出navigationRef。.

// App.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}

export default function App() {
return (
<NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
);
}

那么你可以导入它里面有PushNotification.configure()

// notification-service.js
import PushNotification from 'react-native-push-notification';
import { navigationRef } from './App';
/* Your other code */
PushNotification.configure({
onNotifications: (notification) => {

// Now you'll have access to the navigation object's function here...
}
})

你可以从这里的文档中获得更多的清晰度:navigating-without-navigation-prop

尝试使用React Native Firebase

的例子:

import React, { useState, useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
const navigation = useNavigation();
const [loading, setLoading] = useState(true);
const [initialRoute, setInitialRoute] = useState('Home');
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
}
setLoading(false);
});
}, []);
if (loading) {
return null;
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={initialRoute}>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</Stack.Navigator>
</NavigationContainer>
);

最新更新