컴퓨터뽀개버리기

React Native 튜토리얼(style, layout) 본문

대학생 흔적/ReactNative

React Native 튜토리얼(style, layout)

그순간을기억해 2019. 7. 11. 13:20
반응형
react state

State

  • component를 다루는 데이터는 props와 state 두가지가 있다.
  • props로 설정한 값은 계속 유지되고
    변경될 데이터의 경우 state를 사용해야 한다.
  • 일반적으로 state생성자에서 초기화하고 변경을 하고 싶을 때 setState를 호출한다.
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class Blink extends Component {
  constructor(props) {
    super(props);
    this.state = { isShowingText: true };

    // Toggle the state every second
    setInterval(() => (
      this.setState(previousState => (
        { isShowingText: !previousState.isShowingText }
      ))
    ), 1000);
  }

  render() {
    if (!this.state.isShowingText) {
      return null;
    }

    return (
      <Text>{this.props.text}</Text>
    );
  }
}

export default class BlinkApp extends Component {
  render() {
    return (
      <View>
        <Blink text='I love to blink' />
        <Blink text='Yes blinking is so great' />
        <Blink text='Why did they ever take this out of HTML' />
        <Blink text='Look at me look at me look at me' />
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => BlinkApp);
  • isShowingText를 이용해서 글자와 null값을 번갈아가며 return 해주는 코드이다.
  • setState가 호출되면 해당 App은 component를 다시 렌더링하게 된다.
  • setInterval은 실행 간격으로 정기적으로 호출되는 함수이다. 두번재 인수인 1000은 매 1초마다 호출됨을 의미한다.

Style

react native는 자바스크립트를 사용해서 어플의 스타일을 설정한다. 스타일의 이름은 CSS와 일치한다.
단, backgroundColor는 -> background-color로 조금 다르다.

구성요소가 복잡해지면 StyleSheet.creat로 여러 스타일을 한 곳에 정의하는 방법도 있다.

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

const styles = StyleSheet.create({
  bigBlue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

export default class LotsOfStyles extends Component {
  render() {
    return (
      <View>
        <Text style={styles.red}>just red</Text>
        <Text style={styles.bigBlue}>just bigBlue</Text>
        <Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text>
        <Text style={[styles.red, styles.bigBlue]}>red, then bigBlue</Text>
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfStyles);

코드를 보면 알 수 있듯이 중복되도록 스타일을 적용했다.
예를 들어, styles.bigBlue, style.red이렇게 색이 겹치게 되는데 이때에는 뒤에 적용한 빨간색이 적용된다.

Height & Width

Fixed Dimensions

component의 크기를 설정하는 가장 간단한 방법은 고정 width 와 height 를 추가하는 것이다.
react native의 치수는 픽셀을 의미한다.

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

export default class FixedDimensionsBasics extends Component {
  render() {
    return (
      <View>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} />
        <View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);

이렇게 설정된 크기는 화면의 크기와 상관없이 항상 같은 크기로 보이게 된다

Flex Dimensions

사용 가능한 공간을 기준으로 component를 동적으로 바꾸기 위해선 flex를 사용하면 된다.
보통은 flex:1 은 가능한 모든 공간을 채우기 위해 주어진다. 그리고 그 밑의 자식 구성요소들이 이 공간을 다시 비율로 나눠가지는 것이다,
만약 상위 component의 고정된 넓이/높이가 없거나 flex : 0이면 하위 component는 화면에 보여지지 않는다.

export default class FlexDimensionsBasics extends Component {
  render() {
    return (
      // Try removing the `flex: 1` on the parent View.
      // The parent will not have dimensions, so the children can't expand.
      // What if you add `height: 300` instead of `flex: 1`?
      <View style={{flex: 1}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}} />
        <View style={{flex: 2, backgroundColor: 'skyblue'}} />
        <View style={{flex: 3, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);

Flexbox로 Layout

component는 flexbox알고리즘을 사용해 레이아웃을 지정할 수 있다.
Flexbox는 다양한 화면 크기에서 일관된 레이아웃을 제공하도록 설계되어있다.

FlexDirection

레이아웃 style의 기본 축을 결정한다
디폴트는 column(수직)이다.

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

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // Try setting `flexDirection` to `column`.
      <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

justifyContent

주 축을 따라 자식의 분포를 결정한다
예를 들어 시작, 양 끝에 배치되던가, 균등한 간격으로 배치되는가가 있다.
사용 가능한 옵션

  • flex-start
  • center
  • flex-end
  • space-around
  • space-between
  • space-evenly
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

export default class JustifyContentBasics extends Component {
  render() {
    return (
      // Try setting `justifyContent` to `center`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);

alignItems

보조 축을 따라서 자식 정렬을 결정한다.
사용 가능 옵션

  • row
  • column
  • flex-start
  • center
  • flex-end
  • stretch
    단, stretch효과를 얻으려면 자식은 보조 축을 따라 고정된 치수를 가져서는 안된다. 밑에 코드에서 width:50을 지우기 전까지는 stretch가 동작하지 않는다.
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

export default class AlignItemsBasics extends Component {
  render() {
    return (
      // Try setting `alignItems` to 'flex-start'
      // Try setting `justifyContent` to `flex-end`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'stretch',
      }}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{height: 50, backgroundColor: 'skyblue'}} />
        <View style={{height: 100, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);

더 많은 예시는 여기 문서를 참고하면 된다
https://facebook.github.io/react-native/docs/layout-props

반응형

'대학생 흔적 > ReactNative' 카테고리의 다른 글

React Native Package 설치 및 설정  (0) 2019.07.24
TourAPI 사용법  (0) 2019.07.14
React Native 튜토리얼(textinput, touch, scroll)  (0) 2019.07.11
React Native 시작  (0) 2019.07.11