简体   繁体   中英

How to properly type navigation passed as props with React-Navigation with expo

How do I properly type navigation passed as props to another component? As per the docs

Each screen component in your app is provided with the navigation prop automatically.

And also,

To type check our screens, we need to annotate the navigation prop and the route prop received by a screen.

type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;

I have a navigation component with router:

const App: React.FC = () => {
  const [userMetrics, setUserMetrics] = useState<UserMetrics>(null);
  const Stack = createNativeStackNavigator<RootStackParamList>();
  return (
    <UserMetricsContext.Provider value={{ userMetrics, setUserMetrics }}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="Tests" component={Tests} />
        </Stack.Navigator>
      </NavigationContainer>
    </UserMetricsContext.Provider>
  );
};

And in Home screen I want to receive navigation prop to pass it down further to form which have a button that will navigate to Tests component and pass form data as params:

interface Props {
  navigation: NativeStackScreenProps<RootStackParamList, "Home">;
}

export const Home: React.FC<Props> = ({ navigation }) => {
  const { setUserMetrics } =
    useContext<IUserMetricsContextType>(UserMetricsContext);
  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <HealthCheckForm onSubmit={setUserMetrics} navigation={navigation} />
    </View>
  );
};

and now the problem starts to be visible in form component because typescript is assuming one level too much, I have typed the props like I did in the parent Home component like so:

interface Props {
  onSubmit: React.Dispatch<React.SetStateAction<UserMetrics>>;
  navigation: NativeStackScreenProps<RootStackParamList, "Home">;
}

and typescript wants me to use it like so:

  const submitHandler = (data: UserMetrics) => {
    onSubmit(data);
    navigation.navigation.navigate("Tests", { userMetrics: data });
    console.log(data);
  };

This is not working however, the correct - working and navigating usage is

navigation.navigate("Tests", { userMetrics: data });

and when I navigate to the Tests component and pass the params along, I don't know how to receive them in Test component. I am trying to do it analogically like so:

interface Props {
  navigation: NativeStackScreenProps<RootStackParamList, "Tests">;
}

export const Tests: React.FC<Props> = ({ navigation }) => {
  const { userMetrics } =
    useContext<IUserMetricsContextType>(UserMetricsContext);
  console.log({ params: navigation.route.params });
  return (
    <View>
      <DisplayList />
    </View>
  );
};

And I get yet another error about reading properties of undefined. Thanks

There are solutions for nested Navigators (starting point here: https://reactnavigation.org/docs/nesting-navigators/ ). However, in this case I would suggest not making your HealthCheckForm have any awareness of the navigation state. Just pass it a standard onSubmit() prop and handle all the navigation within the Home component.

Also as a tip make sure to set up your RootStackParamList correctly so that the "tests" route is expecting {userMetrics: YourDataType} . Here is a random example of setting that up.

export type RootStackParamList = {
    myRouteName: undefined;
    tests: { userMetrics: MyDataType }; // TS now expects MyDataType on the props for tests route
    terminalAndMate: {
        departingTerminal: WSFTerminal;
        arrivingTerminal: WSFTerminal;
    };
...

I would also suggest typing your screen props this way instead of as an interface. NativeStackScreenProps can carry params as defined on the rootStackParamList:

type TestsScreenProps = NativeStackScreenProps<RootStackParamList, "tests">;

With those two changes, the tests screen should have props.route.params , which will contain MyDataType.

try: https://reactnavigation.org/docs/5.x/typescript/

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