React Native - 如何从推送通知打开路线

问题描述 投票:9回答:1

我正在使用react-navigationreact-native-push-notification。如何在StackNavigator's回调中打开某个onNotification屏幕?应该工作时:

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

我现在只需要在Android上工作。

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

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

并在onOpen配置中解雇PushNotification

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

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

reactjs react-native push-notification react-navigation
1个回答
7
投票

好吧,好像我要发布自己的解决方案:)

// 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
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.