[React Native] Expo 라이브러리를 사용하여 Splash 이미지 제어하기

호이·2023년 2월 2일
0

React Native

목록 보기
3/10

※ 이 포스트는 클래스형 컴포넌트를 기준으로 작성되었다.

1. 왜 필요한가?

앱을 로딩 중인 경우 로딩화면을 감추고 로고를 표시함으로써 사용자에게 로딩시간 중 상업적 홍보의 효과가 있다.

※ Splash 이미지란?
앱을 실행하였을 때 앱 로딩되는 사이 사용자에게 보여지는 이미지를 말한다. 보통 앱이 로딩 중일 때 사용된다. Expo 라이브러리에서 Splash 이미지를 제어할 수 있는 라이브러리가 존재한다.

2. 과정

expo 프로젝트 내에서 제공하는 expo-splash-screen 라이브러리를 활용하면 쉽게 Splash이미지를 제어할 수 있다.

3. 결과

다음 명령어를 사용하여 expo-splash-screen라는 라이브러리를 설치한다.

npx expo install expo-splash-screen

설치가 완료되면 해당 라이브러리를 import한다.

import * as SplashScreen from "expo-splash-screen";

Splash 이미지가 자동으로 사라지는 것을 막고 sleep함수를 호출하여 3초간 이미지를 보여준 뒤 사라지도록 함수를 정의했다. 해당 함수는 async await를 사용하여 동기적으로 실행되도록 하였다.

async function delay_splash() {
  await SplashScreen.preventAutoHideAsync();
  await sleep(3000);
  await SplashScreen.hideAsync();
}

sleep함수는 Promise를 사용하여 setTimeout을 동기적으로 처리되게 작성하였다.

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

웹뷰가 실행되기 전 함수를 호출하여 Splash 이미지를 보이게 한다.

render() {
    delay_splash();
    return (
      <WebView
        source={{ uri: "https://www.naver.com" }}
        }}
      />
    );
  }

전체 코드는 다음과 같다.

import React from "react";
import * as SplashScreen from "expo-splash-screen";
import { WebView } from "react-native-webview";

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function delay_splash() {
  await SplashScreen.preventAutoHideAsync();
  await sleep(3000);
  await SplashScreen.hideAsync();
}

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    delay_splash();
    return (
      <WebView
        source={{ uri: "https://www.naver.com" }}
      />
    );
  }
}
profile
기억하기 싫어서 기록하는 작은 공간

0개의 댓글