IT 유용한 정보

[ react-native ] 스타일링 방법 2가지, import, module, class 외

JooKit 주킷 2021. 1. 17. 00:26
목차 접기
728x90
반응형

View, Text

import React, { Component } from 'react';
  • react라는 module에서 Component class를 import하는 의미.
  • 그 Component를 상속받는 App이라는 클래스를 생성하는 순서

App 클래스

  • 화면을 렌더링하는 함수가 있고(render() 함수)
    그 안에 return 되는 것들이 화면을 구성하게 된다.
import { View, Text } from 'react-native';
  • 'react-native'라는 module에서 View, Text 클래스를
    import하는 것이다.
  • Button, Image 등 다양한 클래스를 가져와서 사용할 수 있다.
  • Text, Button, Image 등 화면에 출력하려면 View 태그에 감싸져 있어야 한다.

View 태그의 역할

  • 다른 Component들을 감싸주는 역할.
  • View 태그 안에는 여러개의 View태그가 들어가도 된다.
  • View는 화면을 채우는 컨테이너같은 존재이다.

스타일을 주는 방법 2가지

  • 인라인 스타일링(태그 안에 style을 입력)
  • 아래에 따로 빼서 스타일을 지정하는 방법

인라인 스타일링 방법

  • style={{}}
  • { : 첫번째 중괄호는 JSX를
  • {{ : 두번째 중괄호는 객체를 담는 것을 의미한다.
  • marginTop: 50
    • 실제 px 단위는 아니고 폰의 고유 단위
  • react-native의 어떤 Component도 부동소수점을
    이해하지 못한다. 정수로 입력.

아래에서 따로 스타일링하는 방법

  • 'react-native' module로부터 'StyleSheet'라는 클래스를 import 한다.
  • 아래에 변수를 1개 만들고 StyleSheet로부터 create라는 메서드를 불러온다.
  • create 메서드 안에 객체들을 만든다.
  • height를 지우고 flex:1을 준다.
    • flex property는 화면을 채우는 컴포넌트들 간의
      차지하는 영역의 비율같은 지표.
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: {
    backgroundColor: 'green',
    flex: 1,
    marginTop: 50,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

export default App;


style 객체 추가해서 응용

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: {
    backgroundColor: 'green',
    flex: 1,
    paddingTop: 50,
    justifyContent: 'center',
    alignItems: 'center'
  },
  subView: {
    backgroundColor: 'yellow',
    flex: 1,
    marginBottom: 10,
    width: '50%'
  }, 
  anotherSubView: {
    backgroundColor: 'yellow',
    flex: 2,
    marginBottom: 10,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center'
  },
  mainText: {
    color: 'red',
    fontWeight: 'bold',
    fontSize: 50,
    padding: 20
  }
})

export default App;
728x90
반응형
LIST