如何通过堆栈导航(Stack.Screen)传递道具

时间:2021-01-12 02:50:56

标签: reactjs react-native react-navigation

我正在尝试通过堆栈导航将名为 user 的道具传递给我的许多页面组件,但由于某种原因它无法正常工作。然而道具可以从 Tab Navigation 传递到这个 Stack Navigation 组件(我使用的是嵌套导航)。

const StackNavigator = (props) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home user={props.user} />}
      </Stack.Screen>
        <Stack.Screen
            name="Necessities"
            options={{ headerShown: false }}
        >
            {props => <Necessities user={props.user} />}
        </Stack.Screen>
        <Stack.Screen
            name="Entertainment"
            options={{ headerShown: false }}
        >
            {props => <Entertainment user={props.user} />}
        </Stack.Screen>
        <Stack.Screen
            name="Personal"
            options={{ headerShown: false }}
        >
            {props => <Personal user={props.user} />}
        </Stack.Screen>
      <Stack.Screen
        name="TransactionPage"
        options={{ headerShown: true }}
        component={TransactionPage}
      />
    </Stack.Navigator>
  );
};

我正在使用文档中的方法 https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props 但它不起作用???当我转到我的任何组件(例如 Personal )时,props 未定义。

2 个答案:

答案 0 :(得分:0)

如果你得到一个未定义的 props 你应该传递 {...props} 并调试 user 是否在 props 里面以及你的 <Home /> 正在接收什么 props

//To debug what props you is passing
<Stack.Screen
  name="Home"
  options={{ headerShown: false }}
>
    {props => <Home {...props} />}
</Stack.Screen>

答案 1 :(得分:0)

它不起作用,因为您有 2 个名为 props 的变量并且您引用了错误的变量

const StackNavigator = (props) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home user={props.user} />} // this `props` is for the screen, not from the parent props

你需要做这样的事情:

const StackNavigator = (parentProps) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home {...props} user={parentProps.user} />} // use `parentProps` instead of `props`

但这并不是您手动将道具传递到每个屏幕的理想方式。你应该改用 React Context,这更好,它会简化你的代码。