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

React Native开发:点击A屏按钮如何在B屏触发常驻通知提醒

实现思路

  • 你需要一个全局可访问的通知状态池,用来存储所有待展示的常驻通知,所有页面都可以修改/读取这个状态
  • 首页A点击按钮时,不再弹Alert,而是往状态池里新增一条通知记录
  • 通知页B订阅这个状态池的变化,渲染所有未完成的通知,点击通知后从状态池里移除对应记录即可

步骤1:创建全局通知状态Context

如果你的项目已经接入了Redux、Zustand等状态管理工具,可以直接把通知状态存在全局Store里,跳过这一步直接复用现有状态管理逻辑即可。

// NotificationContext.js
import { createContext, useContext, useState } from 'react';

const NotificationContext = createContext();

export function NotificationProvider({ children }) {
  // 存储所有通知,每个通知带唯一id、内容、是否完成标识
  const [notifications, setNotifications] = useState([]);

  // 新增通知方法
  const addNotification = (content) => {
    const newNotify = {
      id: Date.now().toString(), // 简单生成唯一id,生产环境可替换为uuid
      content,
      completed: false
    }
    setNotifications(prev => [...prev, newNotify]);
  }

  // 完成/移除通知方法
  const removeNotification = (id) => {
    setNotifications(prev => prev.filter(item => item.id !== id));
  }

  return (
    <NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>
      {children}
    </NotificationContext.Provider>
  )
}

// 自定义Hooks方便组件调用
export const useNotification = () => useContext(NotificationContext);

步骤2:把通知Provider包裹在路由根节点外

确保所有Stack页面都能访问到通知状态:

// App.js 你的路由入口文件
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { NotificationProvider } from './NotificationContext';
import HomeScreen from './HomeScreen'; // 你的A屏幕(首页)
import NotificationScreen from './NotificationScreen'; // 你的B屏幕(通知页)

const Stack = createStackNavigator();

export default function App() {
  return (
    <NotificationProvider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Notification" component={NotificationScreen} />
          {/* 其余你的路由页面 */}
        </Stack.Navigator>
      </NavigationContainer>
    </NotificationProvider>
  )
}

步骤3:修改首页A的按钮点击逻辑

替换原来的Alert弹出逻辑,改为新增通知:

// 首页A(HomeScreen.js)代码调整
import { useNotification } from './NotificationContext';

// ...其余代码省略
const { addNotification } = useNotification();
// 可选:如果需要点击后直接跳转到通知页,引入useNavigation拿到navigation对象
// const navigation = useNavigation();

const taskedClick = () => {
  // 替换原来的Alert.alert
  addNotification('I am the ALERT');
  // 可选:点击后直接跳转到通知页,不需要可以删掉
  // navigation.navigate('Notification');
}

return (
        <View> 
             <Button onPress={taskedClick}
             style={styles.leftButton}
             type="solid"
             title={post.leftUser.leftButton}
             />
        </View>
)

步骤4:通知页B渲染常驻通知

// 通知页B(NotificationScreen.js)代码
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { useNotification } from './NotificationContext';

export default function NotificationScreen() {
  const { notifications, removeNotification } = useNotification();

  return (
    <View style={styles.container}>
      <Text style={styles.title}>通知中心</Text>
      {notifications.length === 0 ? (
        <Text style={styles.emptyText}>暂无通知</Text>
      ) : (
        notifications.map(notify => (
          <TouchableOpacity 
            key={notify.id} 
            style={styles.notifyItem}
            onPress={() => removeNotification(notify.id)}
          >
            <Text>{notify.content}</Text>
            <Text style={styles.tip}>点击完成任务</Text>
          </TouchableOpacity>
        ))
      )}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 16,
  },
  emptyText: {
    color: '#999',
    textAlign: 'center',
    marginTop: 32,
  },
  notifyItem: {
    padding: 16,
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    marginBottom: 12,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  tip: {
    fontSize: 12,
    color: '#666',
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:03