首页 > 解决方案 > 如何在推送通知中按下操作按钮时调用函数反应本机

问题描述

我能够生成通知以及操作按钮,但是如何根据用户按下的按钮调用 onpress 事件?在这里是或否提前谢谢

从“react-native-push-notification”导入 PushNotification;

function configure() {
  PushNotification.configure({
    // (required) Called when a remote is received or opened, or local notification is opened
    onNotification: function (notification) {
      console.log('NOTIFICATION:', notification);
      // process the notification
      // (required) Called when a remote is received or opened, or local notification is opened
      notification.finish();
    },
    // IOS ONLY (optional): default: all - Permissions to register.
    permissions: {
      alert: true,
      badge: true,
      sound: true,
    },
    // Should the initial notification be popped automatically
    // default: true
    popInitialNotification: true,
    /**
     * (optional) default: true
     * - Specified if permissions (ios) and token (android and ios) will requested or not,
     * - if not, you must call PushNotificationsHandler.requestPermissions() later
     * - if you are not using remote notification or do not have Firebase installed, use this:
     *     requestPermissions: Platform.OS === 'ios'
     */
    requestPermissions: true,
    requestPermissions: Platform.OS === 'ios',
    'content-available': 1,
  });
}


function givenotification(title, message) {
  PushNotification.localNotification({
    channelId: 'channel',
    message: message, // (required)
    title: title,
    message: message, // (required) 
  actions: ["Yes", "No"]
  });
}

标签: react-nativereact-native-iosreact-native-firebase

解决方案


您可以按照以下代码设置操作:

export const App = () => {
  const [permissions, setPermissions] = useState({});

  /**
   * By calling this function, a notification with category `userAction` will have action buttons
   */
  const setNotificationCategories = () => {
    PushNotificationIOS.setNotificationCategories([
      {
        id: 'userAction',
        actions: [
          {id: 'open', title: 'Open', options: {foreground: true}},
          {
            id: 'ignore',
            title: 'Desruptive',
            options: {foreground: true, destructive: true},
          },
          {
            id: 'text',
            title: 'Text Input',
            options: {foreground: true},
            textInput: {buttonTitle: 'Send'},
          },
        ],
      },
    ]);
  };

  useEffect(() => {
    PushNotificationIOS.addEventListener('notification', onRemoteNotification);
  });

  const onRemoteNotification = (notification) => {
    const actionIdentifier = notification.getActionIdentifier();

    if (actionIdentifier === 'open') {
      // Perform action based on open action
    }

    if (actionIdentifier === 'text') {
      // Text that of user input.
      const userText = notification.getUserText();
      // Perform action based on textinput action
    }
  };
};

有关更多信息,您可以访问该库的官方文档。

https://github.com/zo0r/react-native-push-notification


推荐阅读