如何在 React Native 中为推送通知添加点击操作
How to add click action for push notification in React native
我想在点击远程推送通知后导航到特定的应用程序屏幕。
我怎样才能用本机反应来实现这个。我正在使用 react-native-push-notification 库
react-native-push-notification 有一个 on notification press handler -> onNotification 每次用户按下或收到通知时都会调用它(这来自 react-native-push-notification 文档)。在应用程序中,您创建一个 NavigationService 组件,它使用 App.js 文件中设置的顶级导航器引用。使用此导航器,在 onNotification 回调中,您可以导航到应用程序中的任何屏幕,并使用您收到的通知数据用于您的目的,这些数据可以通过导航器(在其状态下)传递到导航屏幕。一些伪代码可能如下所示:
NotificationService.js:
import NavigationService from './NavigationService';
import PushNotification from "react-native-push-notification";
PushNotification.configure({
onNotification: function(notification) {
const { data } = notification;
NavigationService.navigate('Screen', { notificationData: data });
}
});
NavigationService.js:
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
编辑:您还必须创建一个 AppContainer,(它位于您的 App.js 中)
import { createSwitchNavigator } from 'react-navigation';
import { createAppContainer } from 'react-navigation';
const AppContainer = createAppContainer(createSwitchNavigator({...Screens}));
export default class App extends React.Component {
...
render() {
return (
<View>
<AppContainer ref={ (navigatorRef) => { NavigationService.setTopLevelNavigator(navigatorRef); } } />
</View>
)
}
}
我想在点击远程推送通知后导航到特定的应用程序屏幕。 我怎样才能用本机反应来实现这个。我正在使用 react-native-push-notification 库
react-native-push-notification 有一个 on notification press handler -> onNotification 每次用户按下或收到通知时都会调用它(这来自 react-native-push-notification 文档)。在应用程序中,您创建一个 NavigationService 组件,它使用 App.js 文件中设置的顶级导航器引用。使用此导航器,在 onNotification 回调中,您可以导航到应用程序中的任何屏幕,并使用您收到的通知数据用于您的目的,这些数据可以通过导航器(在其状态下)传递到导航屏幕。一些伪代码可能如下所示:
NotificationService.js:
import NavigationService from './NavigationService';
import PushNotification from "react-native-push-notification";
PushNotification.configure({
onNotification: function(notification) {
const { data } = notification;
NavigationService.navigate('Screen', { notificationData: data });
}
});
NavigationService.js:
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
编辑:您还必须创建一个 AppContainer,(它位于您的 App.js 中)
import { createSwitchNavigator } from 'react-navigation';
import { createAppContainer } from 'react-navigation';
const AppContainer = createAppContainer(createSwitchNavigator({...Screens}));
export default class App extends React.Component {
...
render() {
return (
<View>
<AppContainer ref={ (navigatorRef) => { NavigationService.setTopLevelNavigator(navigatorRef); } } />
</View>
)
}
}