[React Native] View, Text, StyleSheet Component

2020. 12. 24. 01:53React/React Native

1. 사전 작업

1) 새로운 프로젝트 생성

react-native init --version 0.61.5 react_test
cd react_test
code .
// 터미널 1
npm start

// 터미널 2
react-native run-ios

2) index.js 확인

App.js는 기본 화면에 대한 파일이라면, index.js는 앱을 시작하는 곳이다.

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
코드 설명
import {AppRegistry} from 'react-native'; AppRegistry imort
import App from './App'; App.js
import {name as appName} from './app.json'; app.json에 있는 name(프로젝트명)을 appName으로 전달
AppRegistry.registerComponent(appName, () => App); app.json에서 가져온 appName, App.js를 인자로 받음

3) App.js

React라는 모듈에서 Component 클래스를 가져오고, 이를 상속받는 App 클래스를 생성한다. 내부에는 화면을 랜더링하는 함수가 존재하고, 그 내부에서 반환하는 값이 화면을 구성하는 요소이다.

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

class App extends Component {
  render() {
    return (
      <View>
        <Text>Hello World</Text>
      </View>
    )
  }
}

export default App;

 

 

 

2. View, Text

기본적으로 View와 Text는 react-native 모듈에서 가져온 클래스이다. View와 Text가 아니여도 Button, Image 등 원하는 클래스를 가져와서 사용할 수 있다.

 

화면을 출력하기위해서는 <View> 태그가 필요하며, <View> 태그 안에 <View> 태그가 여러 개 존재할 수 있다.

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

class App extends Component {
  render() {
    return (
      <View>
        <View>
        <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
      </View>
    )
  }
}

export default App;

 

 

 

3. Style

여기서 텍스트의 위치, 색상, 크기 등 속성을 주기 위해서는 별도의 작업이 필요하다. 이 작업에는 크게 두 가지 방법으로 나뉜다.

  • 태그 내부에 정의해주는 Inline 방법 (1)
  • 별도의 Style 지정 (2)

 

(1)

여기서 margin과 같이 지정된 숫자는 픽셀 단위가 아닌 실제 사용하고 있는 핸드폰의 고유 단위이다. 또한 React Native의 모든 컴포넌트는 float와 같은 부동 소수점을 해석하지 못하기에 정수를 기입해야한다.

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

class App extends Component {
  render() {
    return (
      <View style={{ backgroundColor: 'green', marginTop: 50, height: '50%'}}>
        <View>
        <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
      </View>
    )
  }
}

export default App;
코드 설명
margin View가 다른 컴포넌트와의 간격을 띄울 때 사용 (외부)
padding View 내부의 다른 컴포턴트와의 간격을 띄울 때 사용 (내부)

Inline 방법

(2)

별도의 Style을 지정하는 경우에는 react-native 모듈에서 StyleSheet 클래스를 이용하면 된다.

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

class App extends Component {
  render() {
    return (
      <View style={styles.mainView}>
        <View>
        <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
        <View>
          <Text>Hello World</Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    backgroundColor: 'green', 
    paddingTop: 50, 
    alignItems: 'center',
    justifyContent: 'center'
  }
})

export default App;
코드 설명
flex 화면을 채우는 컴포넌트간의 비율을 나타낸다.
alignItem 수평 정렬
justifyContent 수직 정렬

※ 예를 들어 View가 두개인데, A View의 flex값이 1이고 B View의 3이라면 A는 1/4, B는 3/4 만큼 채워진다. 

StyleSheet 방법

다른 View와 Text에도 Style을 적용했을 경우는 다음과 같다.

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

class App extends Component {
  render() {
    return (
      <View style={styles.mainView}>
        <View style={styles.subView}>
        <Text style={styles.mainText}>Hello World</Text>
        </View>
        <View style={styles.subView}>
          <Text>Hello World</Text>
        </View>
        <View style={styles.anotherSubView}>
          <Text style={styles.mainText}>Hello World</Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    backgroundColor: 'green', 
    paddingTop: 50, 
    alignItems: 'center',
    justifyContent: 'center'
  },

  subView: {
    flex: 1, 
    backgroundColor: 'yellow',
    marginBottom: 10
  },

  anotherSubView: {
    flex: 2,
    backgroundColor: 'yellow',
    marginBottom: 10,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center'
  },
  /*
  - 첫 번째 subView.flex + 두 번째 subView.flex + anotherSubView.flex = 4
  - 첫 번째 View, 두 번째 View: subView.flex/4
  - 세 번째 View: 2/4 = 1/2
  */

  mainText: {
    fontSize: 50,
    fontWeight: 'bold',
    color: 'red',
    padding: 20
  }
  /*
  - subView에 width값을 지정하지 않았기 때문에 폰트 사이즈에 따라 크기가 달라진다.
  - subView에 width값을 지정할 경우에는 폰트가 줄바꿈하면서 View의 크기에 맞춰 조정된다.
  */
})

export default App;

 

그 외 Style 적용

728x90

'React > React Native' 카테고리의 다른 글

[React Native] ScrollView, TextInput  (0) 2020.12.24
[React Native] Touch Event, Button  (0) 2020.12.24
[React Native] 필요한 React 지식  (0) 2020.12.23
[React Native] 새 프로젝트 생성  (0) 2020.12.23