React Navigation - Stack.Navigator screenProps 不工作

React Navigation - Stack.Navigator screenProps not working

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

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