5.4.2 useRoute

    useRouteuseNavigation과 비슷하게, Screen이 아닌 컴포넌트에서 route 객체를 사용할 수 있게 합니다. DetailScreen 컴포넌트에서 route.params.id를 보여주는 TextIDText라는 컴포넌트로 따로 분리시키고, 해당 컴포넌트에서 useRoute Hook을 사용해 route 객체를 사용해보세요.

    screens/DetailScreen.js

    import React, {useEffect} from 'react';
    import {View, Text, StyleSheet, Button} from 'react-native';
    import {useRoute} from '@react-navigation/native';
    
    function IDText() {
      const route = useRoute();
      return <Text style={styles.text}>id: {route.params.id}</Text>;
    }
    
    function DetailScreen({route, navigation}) {
      useEffect(() => {
        navigation.setOptions({
          title: `상세 정보 - ${route.params.id}`,
        });
      }, [navigation, route.params.id]);
      return (
        <View style={styles.block}>
          <IDText />
            <View style={styles.buttons}>
              <Button
                title="다음"
                onPress={() => navigation.push('Detail', {id: route.params.id + 1})}
              />
              <Button title="뒤로가기" onPress={() => navigation.pop()} />
              <Button title="처음으로" onPress={() => navigation.popToTop()} />
            </View>
          </View>
        );
      }
    
    (...)

    Detail 1 열기 버튼을 눌러서 DetailScreen을 띄웠을 때 화면에 id 값이 제대로 나타나는지 확인해보세요.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.