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

React Native中如何向Stack Screens传递自定义props

问题根源

React Navigation 的 <Stack.Screen> 组件只识别官方约定的属性(如name、component、options等),你直接在标签上写data={data}、handleSubmit={handleSubmit}属于自定义属性,不会被自动注入到对应的屏幕组件中,因此Addtask组件内访问handleSubmit会得到undefined。

修复方法

方法1:通过渲染回调传参(适配你当前代码的最小改动方案)

将<Stack.Screen>的component属性替换为children渲染函数,手动把导航内置props和你自定义的props一起传给目标组件即可。修改App.js的导航部分代码:

return (
  <NavigationContainer>
    <Stack.Navigator screenOptions={{header: ()=>null}}>
      <Stack.Screen name='Welcome' component={Welcome}></Stack.Screen>
      <Stack.Screen name='Tasklist'>
        {(screenProps) => <Tasklist {...screenProps} data={data} />}
      </Stack.Screen>
      <Stack.Screen name='Addtask'>
        {(screenProps) => <Addtask {...screenProps} handleSubmit={handleSubmit} />}
      </Stack.Screen>
    </Stack.Navigator>
  </NavigationContainer>
);

说明:渲染回调的参数里包含React Navigation自动注入的navigation、route等内置属性,通过{...screenProps}展开传递后,组件中原有的导航逻辑(比如navigation.goBack())可以正常使用,你自定义的props也会正常传入。

另外你当前Addtask组件里的Save按钮逻辑有遗漏:直接绑定onPress={handleSubmit}不会把输入框的task值传入提交函数,需要改成箭头函数显式传参,同时可以补上提交后的清空输入、返回列表逻辑:

<Button 
  color={'green'} 
  onPress={() => {
    handleSubmit(task);
    setTask('');
    navigation.goBack();
  }} 
  title="Save"
/>

方法2:使用Context做全局状态共享(适合多页面复用状态的场景)

如果后续多个屏幕都需要访问待办数据和操作方法,可以用React Context在App层统一提供状态,避免逐层传参:

  1. 在App.js中创建待办相关的Context,用Provider包裹导航容器:
import React, { useState, createContext, useContext } from "react";
// 其他导入保持不变

const TodoContext = createContext(null);

export default function App() {
  const [data,setData] = useState([]);

  const handleSubmit = (task) => {
    setData((prevtodo)=> {
      return [
        {
          task:task,
          key: Math.random().toString(),
        },
        ...prevtodo
      ];
    });
  }
  
  return (
    <TodoContext.Provider value={{ data, handleSubmit }}>
      <NavigationContainer>
        <Stack.Navigator screenOptions={{header: ()=>null}}>
          <Stack.Screen name='Welcome' component={Welcome} />
          <Stack.Screen name='Tasklist' component={Tasklist} />
          <Stack.Screen name='Addtask' component={Addtask} />
        </Stack.Navigator>
      </NavigationContainer>
    </TodoContext.Provider>
  );
}
  1. 在需要使用状态的组件中,直接通过useContext取值即可,不需要额外在导航配置里传参,比如Addtask.js:
// 导入App.js中导出的TodoContext
const Addtask = ({navigation}) => {
  const { handleSubmit } = useContext(TodoContext);
  const [task, setTask] = useState("");
  // 其余组件逻辑保持不变
}

Tasklist组件要访问data时,也用同样的方式从Context中获取即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:51:47