반응형
250x250
Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

가끔 보자, 하늘.

React Native로 앱 개발 - 02. UI 적용 본문

개발 이야기/개발 및 서비스

React Native로 앱 개발 - 02. UI 적용

가온아 2020. 2. 23. 14:41

이번 글에서는 간단한 UI를 적용해 보겠습니다.

 

React native 설치 및 프로젝트 세팅 방법은 앱 개발 - 01 을 참고하시기 바랍니다.

 

앱 개발 - 01 에서 생성한 firstApp 생성된 프로젝트가 있다고 가정한 상태로 설명하겠습니다. 프로젝트가 생성되지 않았다면 앱 개발 - 01를 참고해서 우선 프로젝트를 생성하고 다시 이 글로 돌아와 주세요.

 

이 글에서는 UI를 다룰 때 필요한 주요 기능을 예제를 통해 정리해 보겠습니다. 순서는 아래와 같습니다. 

 

  • React Native Elements 로 UI 구현
  • Layout 설정
  • React Native Navigation 사용하기
  • Popup 구현

React Native Elements 로 UI 구현

 

UI 객체 구현은 React Native Elements (이하 RNE) 을 사용했으며, 설정 절차와 사용 방법만 간단히 언급하겠습니다.

 

생성한 프로젝트의 root에서 RNE를 아래와 같이 설치해 주세요.

# react native elements를 설치합니다.
npm i react-native-elements --save

# vector icons을 설치합니다.
npm i --save react-native-vector-icons

# 사용하는 react native version은 0.61.5 버전이라 link 과정은 생략합니다.

 

처음으로 버튼을 화면에 하나 그려보겠습니다. 

 

App.js 파일을 열어 아래와 같이 고쳐보세요.

import React from 'react';

import {
  SafeAreaView,
} from 'react-native';

import { Button } from 'react-native-elements';

const App: () => React$Node = () => {
  return (
      <SafeAreaView>
         <Button title="Hello World!!" />
      </SafeAreaView>
  );
};

export default App;

SafeAreaView 키워드는 어떤 디바이스에서든 기본 화면 안쪽에 출력할 수 있는 영역을 의미합니다. 그 외 여러 키워드들이 앞으로 쓰여질텐데 이 글에서는 Interface를 사용하는데 필요한 부분만 설명을 하도록 하겠습니다. 그 외 키워드들은 공식 문서를 참고하시기 바랍니다.

 

실행하면 아래와 같은 결과를 볼 수 있습니다.

 

공식 문서 중 Customization 부분은 꼭 확인해 보시고 다음으로 넘어가세요.

 

Layout 설정

다음에는 화면을 1:1:2로 삼 분할 하고 중앙 레이어에 버튼을 넣어보겠습니다. 

 

일단 테스트 코드를 먼저 복사해서 테스트 해보시기 바랍니다. 

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

import { Button } from 'react-native-elements';

const App: () => React$Node = () => {
  return (
      <SafeAreaView style={{marginTop : 50, flex: 1}}> // (1)
        <View style={{flex: 1, backgroundColor:'#EE2C38'}}>  // (2-1)
        </View>

        <View style={{flex: 1, backgroundColor:'#FAA030'}}>  // (2-2)
          <Button raised title="Hello World!!" /> 
        </View>

        <View style={{flex: 2, backgroundColor:'#32B76C'}} /> // (2-3)
      </SafeAreaView>
  );
};

export default App;

flex는 아이템을 어떻게 화면을 채울지를 결정하는 키워드입니다. 값은 화면의 비율을 설정합니다. 2-1/2/3을 보면, 같은 depth에 세 개의 flex가 있고 각각이 1, 1, 2 라고 설정되어 있다면 해당 영역을 1:1:2의 화면 비율로 나누겠다는 설정입니다.

 

레이아웃에 대한 보다 상세 내용은 이 링크 를 참고하세요.

 

화면 레이아웃을 잡아 봤으니 이제 페이징 처리를 해보겠습니다. 

 

React Native Navigation 사용하기

모바일은 보통 단일 화면으로 구성되기 때문에, React Native 에서는 화면 전환을 위해 React Native Navigation이라는 모듈을 주로 사용합니다. 

 

우선 필요한 모듈을 설치합니다. 

npm install @react-navigation/native @react-navigation/stack

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

# ios일 경우 cocoapods로 필요한 라이브러리를 설치해야 합니다.
cd ios
pods install
cd ..

추가 모듈을 설치할 때 에뮬레이터는 끄고 설치 후 재실해 하시기 바랍니다. 

 

App.js에 아래 코드를 복사한 후 재실행 해보시기 바랍니다. 

import 'react-native-gesture-handler';
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {
  SafeAreaView,
  View,
  Text
} from 'react-native';
import { Button } from 'react-native-elements';

const Stack = createStackNavigator();

const App: () => React$Node = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{title: 'Welcome'}}
        />
        <Stack.Screen name="Second" component={SecondScreen} options={{title: 'SecondPage'}}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

function HomeScreen({navigation}) {
  return (
    <Button
      title="Go to Second Page"
      onPress={() => navigation.navigate('Second', {name: 'Parameter_1'})}
    />
  );
}

function SecondScreen({navigation}, param) {
  return (
    <SafeAreaView style={{marginTop:50, flex:1}}>
      <View style={{flex:2}} />
      <View style={{flex:2}} />
      <View style={{flex:1, justifyContent:'flex-end'}}>
        <Button title="Back"  onPress={() => navigation.goBack()} />
      </View>
    </SafeAreaView>
  );
}

 

우선 App 코드를 NavigationContainer로 전체를 감쌉니다. 그리고 Stack.Navigator 안에 사용할 스크린 화면 내용을 정의 합니다. 

 

Stack.Screen의 속성 중 name은 코드에서 지정자처럼 사용할 이름이며, component는 해당 화면에 대한 모듈명을, option의 title에는 각 페이지의 타이틀 명으로 사용됩니다. option에 대한 상세 정보는 이 링크를 참고하세요.

 

마지막 두 개의 함수는 세부 화면을 정의한 코드입니다. 

 

Popup 구현

이 예제에서는 이전에 다루지 않은 몇 가지 중요 개념이 나오기 때문에 우선 샘플 코드(원본 링크)로 테스트를 해 보시고 아래 설명을 읽어보시기 바랍니다.

import React, { Component } from 'react';
import {
  Modal,
  View,
  Text,
  TouchableHighlight,
  StyleSheet
} from 'react-native';
import { Button } from 'react-native-elements';

testModalVisible = false;

const App: () => React$Node = () => {
  return (
    <ModalExample />
  )
}
export default App;

class ModalExample extends Component {
  state = {
    modalVisible: false
  }
  toggleModal(visible) {
      this.setState({ modalVisible: visible });
  }
  render() {
    return (
       <View style = {styles.container}>
          <Modal animationType = {"slide"} transparent = {false}
             visible = {this.state.modalVisible}
             onRequestClose = {() => { console.log("Modal has been closed.") } }>
             
             <View style = {styles.modal}>
                <Text style = {styles.text}>Modal is open!</Text>
                
                <TouchableHighlight onPress = {() => {
                   this.toggleModal(!this.state.modalVisible)}}>
                   
                   <Text style = {styles.text}>Close Modal</Text>
                </TouchableHighlight>
             </View>
          </Modal>
          
          <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
             <Text style = {styles.text}>Open Modal</Text>
          </TouchableHighlight>
       </View>
    )
  }
}

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
      backgroundColor: '#ede3f2',
      padding: 100
   },
   modal: {
      flex: 1,
      alignItems: 'center',
      backgroundColor: '#f7021a',
      padding: 100
   },
   text: {
      color: '#3f2949',
      marginTop: 10
   }
})

 

React 공식 페이지에는 "A JavaScript library for building user interfaces"라는 문구가 있습니다. 그리고 중앙에 "Component-Based"라는 문구가 떡 하니...!

 

위 예제의 정확한 이해를 위해 Component와 state 그리고 props에 대한 정확한 이해가 필요한데, 예제 중심의 이 글에서 이들을 설명하기는 너무 길어지기 때문에 제가 찾았던 글들 중 가장 잘 설명이 되어 있다고 생각하는 링크들를 아래에 기록했으니 여러분도 꼭 읽어보시기 바랍니다. 

 

절대 설명하기 귀찮아서 그런건 아니...

 

지금까지 React-Native 에 필요한 UI 중요 요소 네 가지를 예제로 알아보았습니다. 

 

다음은 유용한 UI 객체들을 살펴보겠습니다.

반응형