React-Native

14. React-Native ScrollView

Daesiker 2021. 2. 1. 13:36
반응형

1. ScrollView

데이터의 양이 많아서 화면을 넘어가면 스크롤이 생기게 해주는 코어 컴포넌트이다. 스크롤을 빠르게 내리면, 데이터를 처리하는 속도가 스크롤 내리는 속도를 따라가지 못해서 흰색화면만 보일 수 있다.

—Example

import React from 'react';
import {StyleSheet, Text, SafeAreaView, ScrollView} from 'react-native';

const App = () => {
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView style={styles.scrollView}>
        <Text style={styles.text}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
        </Text>
      </ScrollView>
    </SafeAreaView>
  )
}
  

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    backgroundColor: 'orange',
    marginHorizontal: 20,
  },
  text: {
    fontSize: 42
  }
});

export default App;

→ Tex 폰트의 사이즈를 크게해서 화면크기보다 크게 한뒤 ScrollView를 적용한 코드

—Props

  • horizontal : true이면 스크롤 뷰의 데이터가 가로로 정렬(default : false)
  • pagingEnabled : true이면 데이터를 collectionView처럼 페이징 할 수 있음(default : false)

    ❗ScrollView에서 크기를 잡는 것이 아닌 자식 뷰에서 크기를 잡아야한다.

  • contentOffset({x : number, y: number}) : 시작지점을 수동으로 설정 가능하다.
  • indicatorStyle: 스크롤 표시기의 스타일을 지정한다.

    — default : 다크모드일땐 'white', 라이트모드일땐 'black'

    — white : 흰색으로 표시

    — black : 검정색으로 표시

  • showsHorizontalScrollIndicator : 현재 스크롤의 위치를 표시한다.(default : true)
  • scrollEnabled : false이면 스크롤을 할 수 없다.(default : true)
  • refreshControl : scrollView가 새로고침을 할수있게 만드는 속성이다. [하단 참조]

Methods

  • flashScrollIndicators() : 스크롤의 위치를 일시적으로만 표시한다.
    flashScrollIndicator();

  • scrollTo() : 지정한 x, y좌표로 이동하는 함수
    scrollTo({x : 0, y: 0, animation: true})

  • scrollToEnd() : scrollview의 가장 아래로 가는 함수
    scrollToEnd({animated: true, duration: 500})
    //0.5초 뒤에 애니매이션을 통해 가장 마지막으로 넘어간다.


2. RefrechControl

ScrollView나 ListView에서 데이터가 수정되었을 때 새로고침기능을 할 수 있게 도와주는 컴포넌트이다.

데이터가 수정되는 동안 refresh control을 생성하고 완료되면 새로운 데이터가 있는 View를 보여준다.

—Example

import React, {useState, useCallback} from 'react';
import {StyleSheet, Text, SafeAreaView, ScrollView, RefreshControl} from 'react-native';

//timeout의 시간만큼 함수를 지연하고 처리하는 함수 생성
const wait = (timeout) => {
  return new Promise(resolve => {
    setTimeout(resolve, timeout);
  });
}

const App = () => {
  const [refreshing, setRefreshing] = useState(false);

  //refreshcontrol을 호출할 때 실행되는 callback함수
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    wait(2000).then(() => setRefreshing(false));
  }, [])

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollView}
        refreshControl = {
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        <Text>Pull down to see RefreshControl indicator</Text>
      </ScrollView>
    </SafeAreaView>
  )
}
  

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'orange',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

→ refreshControl함수 호출시 2초동안 실행되는 함수가 실행되고 그 다음에 scrollView를 reload하여 보여준다.

—Props

  • refreshing(boolean) : refresh할지 여부를 알려주는 속성이다. false일 때는 실행하지 않고 true일 때 실행을 한다.
  • onRefresh(function) : refresh를 시작할 때 호출되는 함수이다. 이 함수 내에서 refreshing 속성을 true로 설정을 하고 데이터에 관한 함수를 작성한 뒤 다시 refreshing 속성의 값을 false로 바꾼다.

IOS만 가능

  • tintColor(string) : indicator의 색상을 변경시켜준다.
  • title(string) : indicator 아래의 타이틀을 지정하는 속성이다.
  • titleColor(string) : 타이틀의 색상을 변경시켜준다.

반응형