screen 앱의 각 구성 요소는 navigation에서 자동으로 props와 함께 제공된다.
navigation props는 모든 구성요소에 전달 되지 않는고 구성 요소만 자동으로 받는다. 예를 들어 구성 요소를 정의하고 자식으로 렌더링하는 경우 해당 구성 요소에 접근 할 수 없다. 그러나 구성요소의 props에 접근하려면 hooks를 사용할 수 있다.
현재 navigator의 종류에 따라 prop에 몇 가지 추가 기능이 있다.
navigation과 대부분의 상호 작용에는 navigate, goBack 및 setParams가 포함되어있다.
navigation.navigate(name, params)
function HomeScreen({ navigation: { navigate } }) {
return (
<View>
<Text>This is the home screen of the app</Text>
<Button
onPress={() =>
navigate('Profile', { names: ['Brent', 'Satya', 'Michaś'] })
}
title="Go to Brent's profile"
/>
</View>
);
}
navigator의 이전화면으로 돌아갈 수 있다.
기본적으로 goBack 다음에서 호출된 화면으로 돌아간다.
function ProfileScreen( { navigation: { goBack } } ) {
return (
<View>
<Button onPress={() => goBack()} title="이전" />
</View>
)
}
예시)
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });
// D -> A 화면
// D Screen
navigation.navigate({ key: SCREEN_KEY_A });
네비게이터 상태를 새 상태로 바꿀 수 있다.
navigation.reset({
index: 0,
routes: [{ name: 'Profile' }],
});
지정된 상태 객체 reset은 기존 탐색 상태를 새 탐색 상태로 대체한다. 즉, 기존화면을 제거하고 새 화면을 추가한다. 상태를 변경할 때 기존 화면을 유지하려면 dispatch를 사용할 수 있다.
setParams()의 매개변수를 업데이트 할 수있다.
function ProfileScreen({ navigation: { setParams } }) {
return (
<Button
onPress={() =>
setParams({
friends:
route.params.friends[0] === 'Brent'
? ['Wojciech', 'Szymon', 'Jakub']
: ['Brent', 'Satya', 'Michaś'],
title:
route.params.title === "Brent's Profile"
? "Lucy's Profile"
: "Brent's Profile",
})
}
title="Swap title and friends"
/>
);
}
setOptions는 구성 요소 내에서 화면 옵션을 설정할 수 있다. 컴포넌트의 props, state, context를 사용하여 화면을 구성해야 하는 경우에 유용하다.
function ProfileScreen({ navigation, route }) {
const [value, onChangeText] = useState(route.params.title);
useEffect(() => {
navigation.setOptions({
title: value === '' ? 'No title' : value,
});
}, [navigation, value]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={onChangeText}
value={value}
/>
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
이렇게 하면 옵션 업데이트 지연이 사용자에게 눈에 띄지 않게 된다. 또한 지연 로드 화면에서도 작동한다. useLayoutEffect는 업데이트 지연을 줄이는데 사용할 수도 있다. 그러나 웹을 지원하고 서버 측 렌더링을 수행하는 경우에는 하지 않는 것이 좋다.
화면은 메서드를 사용하여 navigation에 리스너를 추가할 수 있다.
function Profile({ navigation }) {
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
현재 화면에서 포커스가 있는지 확인할 수 있다. 화면에 포커스가 있으면 true를 반환하고 없으면 false를 반환한다.
const isFocused = navigation.isFocused();
dispatch 메서드를 사용하면 navigation state가 업데이트되는 방법을 결정하는 navigation 개체를 보낼 수 있다.
액션을 디스패치하려면 액션 객체를 직접 작성하는 대신 이 라이브러리에서 제공하는 액션 생성자를 사용해야한다.
import { CommonActions } from '@react-navigation/native';
navigation.dispatch(
CommonActions.navigate({
name: 'Profile',
params: {},
})
);
객체를 전달할 때 추가 속성을 지정할 수도 있다.
source : 작업의 소스로 간주되어야 하는 경로의 키이다. 예를 들어 작업은 경로를 지정된 키로 대체한다. 기본적으로 작업을 전달한 경로의 키를 사용한다. 명시적으로 전달하여 이 동작을 재정의할 수 있다.
target : 작업을 적용해야하는 navigation state의 키이다. 기본적으로 작업은 navigator가 처리하지 않는 경우 다른 navigator에 버블링된다. target이 지정되면 동일한 키를 가진 navigator가 작업을 처리하지 않으면 작업이 버블링되지 않는다.
import { CommonActions } from '@react-navigation/native';
navigation.dispatch({
...CommonActions.navigate('Profile'),
source: 'someRoutekey',
target: 'someStatekey',
});