headerLeft : 뒤로가기 버튼을 React 컴포넌트로 대체시켜도 되고,
headerRight : 우측에 버튼을 추가로 달아도 됨.
Configureing Header Bar
Header Buttons
타이틀 우측 버튼 추가
function StackScreen() { return ( <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={{ headerTitle: props => <LogoTitle {...props} />, headerRight: () => ( <Button onPress={() => alert('This is a button!')} title="Info" color="#fff" /> ), }} /> </Stack.Navigator> ); }
setOptions({headerRight
: function})
- 스크린 컴포넌트와 상호작용(navigate 등) 하려면
options
가 아닌navigation.setOptions
로 버튼을 정의해야함. - setOptions로 정의해야 스크린의 props, state, context 등에 접근 가능.
import * as React from 'react'; import { Button, Text, Image } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; function LogoTitle() { return ( <Image style={{ width: 50, height: 50 }} source={require('@expo/snack-static/react-native-logo.png')} /> ); } function HomeScreen({ navigation }) { const [count, setCount] = React.useState(0); React.useLayoutEffect(() => { navigation.setOptions({ headerRight: () => ( <Button onPress={() => setCount(c => c + 1)} title="Update count" /> ), }); }, [navigation, setCount]); return <Text>Count: {count}</Text>; } const Stack = createStackNavigator(); function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={({ navigation, route }) => ({ headerTitle: props => <LogoTitle {...props} />, })} /> </Stack.Navigator> </NavigationContainer> ); } export default App;
백 버튼 재정의 (overriding)
- 스택 네비게이터에선
백 버튼
을 자동으로 생성함. (이전 화면으로 이동)
- 일반적으론 뒤로가기 기능이 필요하므로 그대로 쓰면 되지만, 커스텀도 가능.