인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

경바님의 프로필 이미지

작성한 질문수

따라하며 배우는 리액트 네이티브 기초

react-native-status-bar-height

getStatusBarHeight () 화면UI적용

작성

·

41

·

수정됨

0

 
getStatusBarHeight의 값이 콘솔에 찍히는데 그 값이 화면에 적용되지 않습니다.

import {
  View,
  StyleSheet,
  StatusBar,
  Image,
  Text,
  TouchableOpacity,
  Animated,
  Platform,
} from 'react-native';
import {getStatusBarHeight} from 'react-native-status-bar-height';
import React, {useEffect, useRef} from 'react';
import {SafeAreaView} from 'react-native-safe-area-context';
import Ionic from 'react-native-vector-icons/Ionicons';

const Status = ({route, navigation}) => {
  const {name, image} = route.params;
  const statusBarHeight = getStatusBarHeight();
  const topMargin = Platform.OS === 'ios' ? statusBarHeight : 0;
  console.log('statusBarHeight', statusBarHeight);
  console.log('topMargin', topMargin);

  // Animated.Value(0)의 값을 직접 변경하면 안되기 때문에 useRef를 사용
  const progress = useRef(new Animated.Value(0)).current;

  const progressAnimation = progress.interpolate({
    inputRange: [0, 5],
    outputRange: ['0%', '100%'],
  });

  useEffect(() => {
    Animated.timing(progress, {
      toValue: 5,
      duration: 5000,
      useNativeDriver: false,
    }).start();
  });

  useEffect(() => {
    let timer = setTimeout(() => {
      navigation.goBack();
    }, 5000);

    return () => {
      clearTimeout(timer);
    };
  });

  return (
    <SafeAreaView style={styles.statusContainer}>
      <StatusBar barStyle="light-content" backgroundColor="black" />
      <View style={[styles.topGreyLineContatiner, {top: 18 + topMargin}]}>
        <Animated.View
          style={{
            backgroundColor: 'white',
            height: '100%',
            width: progressAnimation,
          }}
        />
      </View>

      <View style={[styles.headerContainer, {top: 12 + topMargin}]}>
        
      {* ... /*}
      </View>
      <Image style={styles.storyImage} source={image} />
    </SafeAreaView>
  );
};

export default Status;
const styles = StyleSheet.create({
  statusContainer: {
    backgroundColor: 'black',
    height: '100%',
    justifyContent: 'center',
  },
  topGreyLineContatiner: {
    height: 3,
    width: '95%',
    borderWidth: 1,
    backgroundColor: 'grey',
    position: 'absolute',
  },

  headerContainer: {
    padding: 15,
    flexDirection: 'row',
    alignItems: 'center',
    position: 'absolute',
    top: 12,
    left: 0,
    width: '90%',
  },
  headerImageContainer: {
    width: 30,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
  },
//....

});
  console.log('statusBarHeight', statusBarHeight);
  console.log('topMargin', topMargin);

이렇게 했을경우 statusBarHeight 20 , topMargin 20값이 모두 정상적으로 디버깅 툴에 출력됩니다.
그러나 화면상에 ui에 적용되지 않아요.

일부로 const 에 넣어서 사용해봤고, margintTop과 top이 같이 있을경우 가끔 문제가 된다는 글을 봐서 아예 top에 값을 따로 추가하는 방식도 해보았습니다. 그리고 마지막으로 예제 코드를 그대로 가져와서 사용해보았지만 여전히 화면에서 적용이 되지 않습니다.

값이 찍히는 걸 보면 getStatusBarHeight가 동작하긴 하는건데 화면상에서 적용이 안되는 이유가 뭔지 알 수 있을까요?

스크린샷 2025-04-02 오전 11.30.28.png


답변 1

0

인프런 AI 인턴님의 프로필 이미지

안녕하세요, 인프런 AI 인턴입니다.
경바님께서 겪고 계신 문제는 ‘getStatusBarHeight’ 함수의 값이 UI에 적용되지 않는 문제인 것 같습니다.

코드를 살펴보면, ‘topMargin’ 값을 ‘View’ 컴포넌트의 ‘top’ 스타일 속성에 적용하고 계신데요. 이 경우, ‘position: ‘absolute” 스타일을 사용하셨으므로 ‘top’ 속성은 부모 컨테이너를 기준으로 값을 설정하게 됩니다. 하지만, iOS와 Android의 경우 상태 바의 높이를 정확히 계산하는 방법이 조금씩 다를 수 있습니다.

확인해볼 수 있는 몇 가지 방법을 제안드립니다:
1. SafeAreaView 사용 확인: 안전한 영역을 위한 ‘SafeAreaView’를 사용하고 계시므로, ‘top’ 값에 영향을 미칠 수 있습니다. ‘SafeAreaView’는 기본적으로 상태 바와 네비게이션 바를 피하도록 설정되어 있습니다.

  1. 스타일 적용 위치 변경: 직접 ‘SafeAreaView’에 ‘paddingTop’을 ‘topMargin’으로 적용해 보세요. 이렇게 하면 ‘View’ 컴포넌트를 둘러싼 영역 전체에서 패딩을 적용할 수 있습니다.
   <SafeAreaView style={[styles.statusContainer, {paddingTop: topMargin}]}>
  1. 크로스 플랫폼 차이점 확인: React Native에서는 플랫폼(iOS/Android)에 따라 상태 바의 행동이 다를 수 있으므로, iOS 기기와 Android 기기에서 다른 결과가 나올 수 있습니다. 개발 중인 환경에 맞게 조건문을 통해 각각 다르게 처리해야 할 수도 있습니다.

위와 같은 방법으로 문제를 해결할 수 있기를 바랍니다.
추가적인 도움이 필요하시면 언제든지 말씀해 주세요!

출처: react-native
출처: react-native-safe-area-context

경바님의 프로필 이미지

작성한 질문수

질문하기