You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Expo React Native本地通知中实现多操作跳转功能?

Expo Notifications实现多操作通知方案

完全可以通过Expo Notifications实现你要的多操作通知功能,你之前的问题大概率是没正确配置通知的actions参数以及后续的点击事件处理。下面是具体实现步骤和代码示例:

1. 先获取通知权限

使用通知前必须先请求用户授权:

import * as Notifications from 'expo-notifications';

async function requestNotificationPermissions() {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') {
    alert('需要开启通知权限才能使用该功能');
  }
}

2. 调度带操作按钮的通知

调用scheduleNotificationAsync时,在content中添加actions数组定义操作按钮,同时通过data字段携带页面跳转标识:

async function scheduleMultiActionNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: '新消息提醒',
      body: '有人给你发了消息',
      // 定义操作按钮
      actions: [
        {
          title: '去聊天',
          identifier: 'action_chat',
          options: {
            foreground: true, // 点击按钮唤醒APP到前台
          },
        },
      ],
      // 自定义数据,用于判断默认跳转目标
      data: {
        targetScreen: 'profile',
      },
    },
    trigger: {
      seconds: 1, // 立即触发通知,可替换为定时逻辑
    },
  });
}

3. 监听通知点击事件

通过addNotificationResponseReceivedListener区分点击行为,根据actionIdentifier执行不同跳转逻辑:

import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { useEffect } from 'react';

// 假设已定义对应的页面组件
const Stack = createStackNavigator();

function App() {
  const navigationRef = useNavigationContainerRef();

  useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(response => {
      const actionId = response.actionIdentifier;

      if (actionId === Notifications.DEFAULT_ACTION_IDENTIFIER) {
        // 点击通知标题,跳转个人资料页面
        navigationRef.navigate('Profile');
      } else if (actionId === 'action_chat') {
        // 点击"去聊天"按钮,跳转聊天页面
        navigationRef.navigate('Chat');
      }
    });

    return () => subscription.remove();
  }, []);

  return (
    <NavigationContainer ref={navigationRef}>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Profile" component={ProfileScreen} />
        <Stack.Screen name="Chat" component={ChatScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

注意事项

  • 确保安装最新版expo-notifications:执行expo install expo-notifications更新
  • Android需提前配置通知渠道,可通过Notifications.setNotificationChannelAsync创建
  • iOS上操作按钮的foreground属性控制是否唤醒APP到前台

内容的提问来源于stack exchange,提问作者Gautam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:20:24