我用react-navigationreact-native-push-notification.如何在onNotification回调中打开某个StackNavigator's屏幕?应在以下情况下工作:

  • 应用程序已关闭
  • 应用程序在前台
  • 应用程序在后台

我现在只需要它在安卓系统中工作.

我试图在我的组件中将回调函数传递给通知:

_handleClick() {
  PushNotification.localNotification({
    foreground: false
    userInteraction: false
    message: 'My Notification Message'
    onOpen: () => { this.props.navigation.navigate("OtherScreen") },
  })
}

要在PushNotification配置中触发onOpen:

onNotification: function(notification) {
   notification.onOpen()
}

但函数似乎不能传递给通知,除非一个值是一个字符串,它被忽略,导致onOpen未定义.

推荐答案

好吧,看来我得发布我自己的解决方案:)

// src/services/push-notification.js
const PushNotification = require('react-native-push-notification')

export function setupPushNotification(handleNotification) {
  PushNotification.configure({

      onNotification: function(notification) {
        handleNotification(notification)
      },

      popInitialNotification: true,
      requestPermissions: true,
  })

  return PushNotification
}


// Some notification-scheduling component
import {setupPushNotification} from "src/services/push-notification"

class SomeComponent extends PureComponent {

  componentDidMount() {
    this.pushNotification = setupPushNotification(this._handleNotificationOpen)
  }

  _handleNotificationOpen = () => {
    const {navigate} = this.props.navigation
    navigate("SomeOtherScreen")
  }

  _handlePress = () => {
    this.pushNotification.localNotificationSchedule({
      message: 'Some message',
      date: new Date(Date.now() + (10 * 1000)), // to schedule it in 10 secs in my case
    })

  }

  render() {
    // use _handlePress function somewhere to schedule notification
  }

}

React-native相关问答推荐

try 使用JWT-DECODE解码令牌时出错

莫迪德不会停留在屏幕中央

错误:图片:找不到 ID 为1的assets资源 .请判断图像源或打包器

_react2.default.PropTypes.function 未定义

在 React Native 中从 Modal 打开 Modal

react native条件渲染

React中类似于 React Native 中的 FlatList

react-native app.js index.js

React Native 有全局作用scope域吗?如果没有,我该如何模仿它?

React Native - NSNumber 无法转换为 NSString

React-Native: measure测量一个视图

mapDispatchToProps:有什么意义吗?

react-native android应用程序中的underlineColorAndroid is not a valid style property错误

如何使用 Stripe (stripe.js) 和 react-native

React Native STUCK 启动打包器

有react-native复选框的例子吗?

将 setState 与 promise 一起使用后出现错误

如何在 React Native 中禁用图像淡入效果?

将现有的 React Native 项目转换为 Expo

移动应用程序不需要 CORS?