본문 바로가기
React Native/네비게이션

react navigation 배우기 4부 - 헤더 구성하기

by 붕어사랑 티스토리 2023. 2. 13.
반응형

https://reactnavigation.org/docs/headers

 

https://reactnavigation.org/docs/headers/

 

reactnavigation.org

 

 

1. 헤더 제목 설정하기

앞서 배운것처럼 option에 title 항목에 값을 주면 된다

 

function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{ title: 'My home' }}
      />
    </Stack.Navigator>
  );
}

 

 

2. 파라미터 내용을 헤더제목으로 설정하기

파라미터를 헤더제목으로 설정하려면 아래와 같이 arrow function을 이용한다

 

function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{ title: 'My home' }}
      />
      <Stack.Screen
        name="Profile"
        component={ProfileScreen}
        options={({ route }) => ({ title: route.params.name })}
      />
    </Stack.Navigator>
  );
}

 

 

3. 옵션값을 바꾸고 리렌더링 하기, setOptions

앞서 3부에서 파라미터 값을 바꾸고 rerendering 하려면 setParams를 사용했다. 옵션도 마찬가지로 setOptions를 사용하면 된다.

 

/* Inside of render() of React class */
<Button
  title="Update the title"
  onPress={() => navigation.setOptions({ title: 'Updated!' })}
/>

 

 

4. 헤더 스타일 꾸미기

3가지의 prop으로 헤더를 꾸밀 수 있다

 

  • headerStyle : 헤더를 감싸는 View의 style 값이다
  • headerTintColor : 백버튼과 Title 모두 이 프로퍼티의 컬러를 이용한다. 
  • headerTitleStyle : 타이틀의 텍스트 스타일, fontFamily, fontWeight 같은걸 설정하고 싶으면 이 프로퍼티를 이용한다
function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{
          title: 'My home',
          headerStyle: {
            backgroundColor: '#f4511e',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },
        }}
      />
    </Stack.Navigator>
  );
}

 

 

 

5. option값을 common하게 공유하는 방법

각각의 스크린에 통일된 스타일을 적용하고 싶은데, 각각의 스크린마다 옵션값을 똑같이 주는것은 비효율 적이다.

 

이를 해결하는 방법은 Navigator의 screenOptions라는 프로퍼티를 이용하는 것이다. 이를 사용하면 네비게이터 안의 모든 스크린에 공통된 스타일을 줄 수 있다.

 

function StackScreen() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: '#f4511e',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
      }}
    >
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{ title: 'My home' }}
      />
    </Stack.Navigator>
  );
}

 

 

6. 타이틀을 커스텀 component로 바꾸는 법

커스텀 컴포넌트를 만든 뒤 option에 headerTitle 이라는 프로퍼티에 이를 전달하면 된다

 

function LogoTitle() {
  return (
    <Image
      style={{ width: 50, height: 50 }}
      source={require('@expo/snack-static/react-native-logo.png')}
    />
  );
}

function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{ headerTitle: (props) => <LogoTitle {...props} /> }}
      />
    </Stack.Navigator>
  );
}

 

 

7. 헤더에 버튼 추가하는 법

유저와 헤더가 인터렉션 하는 방법은 주로 헤더에 버튼을 추가하는 방법이다.

이는 headerRightheaderLeft 프로퍼티를 이용하여 구현이 가능하다.

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>
  );
}

 

 

 

8. 스크린에서 헤더버튼 설정하는법

공식문서에 이 내용은 왜 있는지 모르겠는데... 딱히 쓸모도 없어보이고.

아무튼 스크린내에서 헤더버튼을 설정하는 방법은 navigate.setOptions를 이용하라 이다.

 

아래 예제는 텅빈 깡통 버튼을 넣었는데 스크린에서 setOptions를 통하여 카운트 하는 기능을 넣은 예제이다

 

테스트해보기

function StackScreen() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={({ navigation, route }) => ({
          headerTitle: (props) => <LogoTitle {...props} />,
          // Add a placeholder button without the `onPress` to avoid flicker
          headerRight: () => (
            <Button title="Update count" />
          ),
        })}
      />
    </Stack.Navigator>
  );
}

function HomeScreen({ navigation }) {
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    // Use `setOptions` to update the button that we previously specified
    // Now the button includes an `onPress` handler to update the count
    navigation.setOptions({
      headerRight: () => (
        <Button onPress={() => setCount((c) => c + 1)} title="Update count" />
      ),
    });
  }, [navigation]);

  return <Text>Count: {count}</Text>;
}

 

 

 

9. 백버튼 꾸미기

백버튼을 꾸미는 방법은 대표적으로 아래 세가지가 있다

 

  • headerBackTitle : 백버튼에 사용되는 string값이다(iOS에서). 기본값은 이전 스크린의 title이거나 Back이다. 만약 이 타이틀 공간이 부족하다면 headerBackTitleVisible을 통해 값을 hide 시킬 수 있다
  • headerBackTitleStyle : headerBackTitle을 꾸미는 프로퍼티이며 fontFamily, fontSize 두가지를 지원한다
  • headerBackImageSource : 헤더 백버튼의 아이콘 이미지를 나타낸다. 기본값으로 ios의 경우 < 모양이고 안드로이드는 <- 이다

 

 

10. 백버튼 override하기

앞서 배운 headerLeft 속성을 이용하면 백버튼을 override한다. 백버튼의 기능 또한 onPress값을 달리 주면 커스터마이징 할 수 있따

반응형

댓글