React native의 RefreshControl 컴포넌트는 스크롤뷰, 플랫리스트, 섹션리스트 컴포넌트에 풀-투-리프레시 기능을 제공하는 내장 컴포넌트입니다. 사용자가 화면을 아래로 당겨서 수동으로 새로고침 동작을 트리거할 수 있습니다.

iOS에서 RefreshControl이 사용하는 기반 기술은 Apple에서 제공하는 UIRefreshControl 컴포넌트입니다. 마찬가지로 안드로이드에서 사용되는 기반 기술은 Google에서 제공하는 SwipeRefreshLayout 컴포넌트입니다.

RefreshControl을 사용하려면 'react-native' 패키지에서 가져와서 풀-투-리프레시 기능을 추가하려는 컴포넌트에 감싸줘야 합니다. 다음은 FlatList와 함께 RefreshControl을 사용하는 방법을 보여주는 코드 스니펫 예시입니다

import React, { useState } from 'react';
import { View, Text, FlatList, RefreshControl } from 'react-native';

const sample = [
  { id: '1', title: 'Item 1' },
  { id: '2', title: 'Item 2' },
  { id: '3', title: 'Item 3' },
  { id: '4', title: 'Item 4' },
  { id: '5', title: 'Item 5' },
];

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

  const onRefresh = () => {
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
    }, 2000);
  };

  const renderItem = ({ item }) => (
    <View style={{ padding: 20 }}>
      <Text>{item.title}</Text>
    </View>
  );

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        data={sample}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      />
    </View>
  );
};

export default App;

이 예제에서는 목록이 현재 새로 고쳐지고 있는지 여부를 추적하는 상태 변수 refreshing과 데이터 불러오기를 수행하고 데이터 불러오기가 완료되면 refreshing 상태 변수를 false로 설정하는 onRefresh 함수를 정의합니다.

그런 다음 FlatList 컴포넌트를 RefreshControl 컴포넌트로 감싸고 refreshing 상태 변수와 onRefresh 함수를 프로퍼티로 전달합니다. 이렇게 하면 사용자가 화면을 아래로 끌어내려 수동으로 새로고침을 트리거할 수 있으며, 그러면 onRefresh 함수가 호출됩니다.

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
http://bit.ly/3Y34pE0

Posted by cipleee