简体   繁体   中英

React Navigation: How to pass a prop to a screen in a nested navigator?

In my React Native app I have the following TabNavigator nested inside an AppNavigator :

const TabNavigator = () => (
    <Tab.Navigator>
      <Tab.Screen component={Screen1} />
    </Tab.Navigator>
);

export const AppNavigator = () => {

  const [loading, setLoading] = useState(false);

  <Stack.Navigator>
    <Stack.Screen component={TabNavigator}/>
    <Stack.Screen component={OtherComponent1}/>
    <Stack.Screen component={OtherComponent2}/>
  </Stack.Navigator>
}

I want to pass the loading hook to Screen1 .

What I've tried:

  1. Putting const TabNavigator etc inside AppNavigator . The problem with this is, AppNavigator re-renders a lot, and therefore Screen1 re-renders and flickers a lot.
  2. Passing loading as a prop to TabNavigator and Screen1 , like <Stack.Screen component={() => <TabNavigator loading={loading}/>}/> and <Tab.Screen component={() => <Screen1 loading={props.loading}/>} /> . The problem with this is is that it gives me this warning about passing an inline function.

What's the best way to approach this?

You can use the Context API to pass the value. https://reactjs.org/docs/context.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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