【问题标题】:React Navigation - Stack.Navigator screenProps not workingReact Navigation - Stack.Navigator screenProps 不起作用
【发布时间】:2020-06-05 16:46:15
【问题描述】:

我有以下代码,它为LoginList 2 个组件创建了一个简单的堆栈导航器。我在带有导航器(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>

【问题讨论】:

    标签: reactjs react-navigation react-props react-navigation-stack


    【解决方案1】:

    你需要使用 React 的 context 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

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2018-01-11
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多