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

React Native中TouchableOpacity点击跳转数据传递问题求助

解决方案

方法1:统一两个按钮的跳转传参逻辑

直接修改第二个TouchableOpacity的跳转逻辑,让它和第一个按钮一样携带notification数据,这样无论点击哪个按钮,Notification页面都能拿到所需数据:

// App组件中修改第二个TouchableOpacity
<TouchableOpacity style={styles.BellButton}
  onPress={() => navigation.navigate("Notification", {item: notification})}>
</TouchableOpacity>

方法2:在Notification页面设置参数默认值

如果不想改动跳转逻辑,可以在Notification页面通过解构赋值给item设置默认值,同时处理route.params为空的情况。需要先把notification数据抽离成可复用模块,方便两个组件导入:

  1. 创建独立的数据文件notificationData.js:
// notificationData.js
export const notification = [
  { id: 1, name: 'David Silbia', message: 'Invite Jo Malone London’s Mother’s', time: 'Just now' },
  { id: 2, name: 'Adnan Safi', message: 'Started following you', time: '20 min ago' },
  { id: 3, name: 'Ronald C. Kinch', message: 'Like you events', time: '9 hr ago' },
  { id: 4, name: 'Clara Tolson', message: 'Join your Event Gala Music Festival', time: 'Wed, 3:30 pm' },
]
  1. 在App和Notification组件中导入并使用:
// App组件
import { notification } from './notificationData';

// Notification组件
import { notification } from './notificationData';

const Notification = ({ route }) => {
  const navigation = useNavigation();
  // 给item设置默认值为全局的notification,同时处理params为空的情况
  const { item = notification } = route.params || {};
  console.log(item)
  return (
    // 页面渲染内容
  )
}

方法3:使用全局状态管理(适合多页面复用数据场景)

如果项目中有多处需要用到notification数据,可以用React Context将数据存为全局状态,这样Notification页面无需依赖跳转参数,直接从全局获取:

  1. 创建Context文件NotificationContext.js:
// NotificationContext.js
import { createContext, useContext } from 'react';
import { notification } from './notificationData';

const NotificationContext = createContext(notification);

export const NotificationProvider = ({ children }) => {
  return (
    <NotificationContext.Provider value={notification}>
      {children}
    </NotificationContext.Provider>
  )
}

export const useNotification = () => useContext(NotificationContext);
  1. 在根组件中包裹NotificationProvider:
// 根组件(如App.js或导航入口组件)
import { NotificationProvider } from './NotificationContext';

const RootApp = () => {
  return (
    <NotificationProvider>
      {/* 你的导航和页面内容 */}
    </NotificationProvider>
  )
}
  1. 在Notification页面直接获取全局数据:
import { useNotification } from './NotificationContext';

const Notification = () => {
  const navigation = useNavigation();
  const item = useNotification();
  console.log(item)
  return (
    // 页面渲染内容
  )
}

内容的提问来源于stack exchange,提问作者MST intern 2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 09:33:17