일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 삼항연산자
- HTML
- 엘리스 AI 트랙 5기
- 간단한 날씨 웹 만들기
- RN 프로젝트
- reactnativecli
- 자바스크립트 날씨 웹 만들기
- 프론트개발
- 엘리스 ai 트랙
- 자바스크립트 reduce()
- 자바스크립트 sort()
- 코딩부트캠프
- JavaScript
- 엘리스
- 리트코드
- 자바스크립트
- leetcode
- 개발일기
- [파이썬 실습] 심화 문제
- 개발공부
- 프로그래머스
- 자바스크립트 split()
- 프론트개발공부
- [AI 5기] 연습 문제집
- 자바스크립트 날씨
- [파이썬 실습] 기초 문제
- 날씨 웹 만들기
- 코드스테이츠
- 부트캠프
- [파이썬 실습] 중급 문제
- Today
- Total
개발조각
[React-native CLI] RN 현재 화면이 어디인지에 따라 상태바 색상 변경하기 본문
[React-native CLI] RN 현재 화면이 어디인지에 따라 상태바 색상 변경하기
개발조각 2024. 3. 27. 15:11이번에는 상태바를 설정해보려 합니다.
일반적인 상태바는 아니고 홈화면일 때는 상태바가 주황색, 홈화면이 아닌 다른 화면일 때에는 상태바가 흰색으로 변하게 해주었습니다.

처음에는 상태바를 App.tsx에 설정하고 싶었지만 App.tsx에 상태바를 설정해 두면
Navigation에 따른 상태바 배경색을 변경할 수 없기 때문에 StackNavigator.tsx에 해주었습니다.
StackNavigator.tsx는 스택내비게이션을 모아둔 곳입니다.
StatusBar 설정
const StackNavigator = () => {
const Stack = createNativeStackNavigator();
return (
<>
<StatusBar
backgroundColor={'#fff'}
barStyle={'dark-content'}
/>
<Stack.Navigator>
<Stack.Screen
name="Main"
component={BottomTabsNavigator}
options={{headerShown: false}}
/>
<Stack.Screen
name="Record"
component={Record}
options={{headerShown: false}}
/>
</Stack.Navigator>
</>
);
};
export default StackNavigator;
Fragment로 감싸고 StatusBar를 넣어주면 잘 작동이 됩니다.
상태바 커스텀 참고 블로그
[RN] Status Bar에 스타일을 적용해보자
여러 앱을 사용하다보면 화면 상단의 Status Bar 에 다양한 스타일이 적용되어 있는 경우를 볼 수 있습니다.Status Bar 에 적절한 스타일을 적용하면 현재 화면에서 보여지는 컨텐츠와의 통일감과 자
velog.io
현재 페이지 이름 출력하기
현재 페이지 이름을 출력하기 위해서는 아래코드를 넣어주면 됩니다.
const navigation = useNavigation();
// 현재 화면의 이름을 가져옵니다.
const currentRouteName = navigation.getCurrentRoute().name;
하지만 이렇게 넣어주면 이와 같은 오류가 발생하게 됩니다.
TypeError: Cannot read property 'name' of undefined This error is located at: in StackNavigator (created by App) in EnsureSingleNavigator in BaseNavigationContainer in ThemeProvider in NavigationContainerInner (created by App) in RecoilRoot_INTERNAL (created by RecoilRoot) in RecoilRoot (created by App) in App in RCTView (created by View) in View (created by AppContainer) in RCTView (created by View) in View (created by AppContainer) in AppContainer in taxi(RootComponent), js engine: hermes
오류 해결하기
이 오류는 내비게이션 상태 객체가 아직 정의되지 않았기 떄문에 발생하는 오류입니다.
위에 코드만 써주게 되면 navigation.getCurrentRoute() 메서드가 호출될 때 네비게이션 상태가 아직 초기화되지 않았기 때문에 오류가 발생하게 됩니다.
이를 해결하기 위해 네비게이션 이벤트를 구독하여 상태를 업데이트해야 됩니다.
const navigation = useNavigation();
const [currentRouteName, setCurrentRouteName] = useState('');
// 현재 페이지 이름 출력
useEffect(() => {
const currentRoute = navigation.addListener('state', () => {
const {name} = navigation.getCurrentRoute();
setCurrentRouteName(name);
});
return currentRoute;
}, [navigation]);
이렇게 useEffect를 사용해 줘서 naviation을 의존성배열에 넣어주어 구독해 주면서 상태를 업데이트해주면 됩니다.
최종 코드
// react, react-native
import React, {useEffect, useState} from 'react';
import {StatusBar} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
// components
import BottomTabsNavigator from './BottomTabsNavigator';
import Record from '../screens/Record';
// style
import Theme from '../styles/Theme';
const StackNavigator = () => {
const Stack = createNativeStackNavigator();
const navigation = useNavigation();
const [currentRouteName, setCurrentRouteName] = useState('');
// 현재 페이지 이름 출력
useEffect(() => {
const currentRoute = navigation.addListener('state', () => {
const {name} = navigation.getCurrentRoute();
setCurrentRouteName(name);
});
return currentRoute;
}, [navigation]);
return (
<>
<StatusBar
backgroundColor={
currentRouteName === 'Home' ? Theme.colors.mainLight : '#fff'
}
barStyle={'dark-content'}
/>
<Stack.Navigator>
<Stack.Screen
name="Main"
component={BottomTabsNavigator}
options={{headerShown: false}}
/>
<Stack.Screen
name="Record"
component={Record}
options={{headerShown: false}}
/>
</Stack.Navigator>
</>
);
};
export default StackNavigator;
'React-Native > [프로젝트] 택시 운행관리 기록장' 카테고리의 다른 글
[React-native CLI] android 핸드폰에 wifi로 연결하기 (0) | 2024.03.28 |
---|---|
[React-native CLI] RN 안드로이드 아이콘 바꾸기 (0) | 2024.03.27 |
[React-native CLI] RN 차트스크린 구현하기 (월간, 연간) (0) | 2024.03.26 |
[React-native CLI] RN에서 그래프 라이브러리 추천 (react-native-gifted-charts 사용방법) (0) | 2024.03.25 |
[React-native CLI] Home화면 기능 구현하기 (0) | 2024.03.23 |