繁体   English   中英

React Navigation - Stack.Navigator screenProps 不起作用

[英]React Navigation - Stack.Navigator screenProps not working

我有以下代码,它为 2 个组件LoginList创建一个简单的堆栈导航器。 我在带有导航器( App.js )的文件中有一个useState挂钩,我想将 setter 和 getter 传递给每个屏幕。 我曾尝试在堆栈导航screenProps上使用screenProps ,但在记录传递给每个组件的 props 后,变量不会出现。

TL;DR我需要将道具从Stack.Navigator传递到每个屏幕

<NavigationContainer>
  <Stack.Navigator screenProps={{setVariable, variable}}>
    <Stack.Screen
      name="Login"
      component={Login}
      options={navOptions}
    />
    <Stack.Screen
      name="List"
      component={List}
      options={navOptions}
    />
  </Stack.Navigator>
</NavigationContainer>

你需要使用 React 的上下文 API

// MyContext.js
export const MyContext = React.createContext();
// App.js
const context = React.useMemo(() => ({
  setVariable,
  variable
}), [variable]);

return (
  <MyContext.Provider value={context}>
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Login"
          component={Login}
          options={navOptions}
        />
        <Stack.Screen
          name="List"
          component={List}
          options={navOptions}
        />
      </Stack.Navigator>
    </NavigationContainer>
  </MyContext.Provider>
);
// Home.js
const variable = React.useContext(MyContext);

https://reactnavigation.org/docs/en/upgrading-from-4.x.html#global-props-with-screenprops

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM