본문 바로가기
React Native

react native 컴포넌트 높이 구하기

by 어느새벽 2025. 12. 22.
반응형

캐러셀을 구현하다가 react-native-reanimated-carousel 라이브러리를 쓰게 됐는데

이 라이브러리가 컴포넌트의 width, height값을 정적으로 주는 것 같았다.

캐러셀 밑에 또 추가한 Pagination 컴포넌트를 두니 캐러셀 내부의 컴포넌트 길이가 길어지면 Pagination이 화면 밑으로 내려가서 가려지는 등의 문제가 생겼다.

그래서 캐러셀의 height 값만은 꼭 동적으로 줘야했는데 이때 onLayout 속성을 사용하니 해결됐다.

 

import Carousel, { ICarouselInstance, Pagination } from "react-native-reanimated-carousel";
// 스크립트 & 스타일시트 로직 생략  

const [carouselHeight, setCarouselHeight] = useState(isTablet ? PAGE_HEIGHT * 0.3 : PAGE_HEIGHT * 0.4);

  // 컴포넌트 높이 측정 함수
  const handleLayout = (event: any) => {
    const { height } = event.nativeEvent.layout;
    if (height > 0 && height !== carouselHeight) {
      setCarouselHeight(height);
    }
  };

 return (
    <View style={styles.container}>
      <Carousel
        autoPlayInterval={4000}
        data={filteredData}
        height={carouselHeight}
        loop={false}
        pagingEnabled={true}
        snapEnabled={true}
        width={isTablet ? PAGE_WIDTH - 96 : PAGE_WIDTH - 32}
        style={styles.carousel}
        mode="parallax"
        modeConfig={{
          parallaxScrollingScale: 1,
          parallaxScrollingOffset: 30,
        }}
        onProgressChange={progress}
        renderItem={({ item }) => {
          const isLightTheme = item.genderCd === "1";

          return isLoading ? (
            <Loader />
          ) : (
          {/* onLayout 속성 추가 */}
            <View style={styles.babyBox} onLayout={handleLayout}>
              <View style={styles.card}>
			{/* 내부 컴포넌트 생략 */}
              </View>
            </View>
          );
        }}
      />
      <Pagination.Basic
        progress={progress}
        data={filteredData}
        dotStyle={styles.dot}
        activeDotStyle={styles.activeDot}
        containerStyle={styles.pagination}
        onPress={(index) => onPressPagination(index)}
      />
    </View>
  );

 

캐러셀의 초기값은 설정해줘야 한다.

이렇게 하면 캐러셀 라이브러리 사용도 문제 없다 ! 

반응형