IT 유용한 정보

[ react-native ] state 사용법 1.

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

State

  • Component에서 rendering되는 데이터를 담고 유지, 관리하는
    자바스크립트 객체이다.

  • component의 rendering되는 데이터를 다루기 때문에
    매우 중요하다.

  • state 값에 따라 화면에 보여지는 output이 달라질 것이다.

  • class component안에서 사용이 가능하고,
    함수 컴포넌트를 정의했다면 state의 활용은 불가하다.

  • state 활용 불가 예시

    const App = () => {
      return (
      )
    }

state 시작

  • 우리는 App이라는 클래스를 사용할 것이기 때문에
    state를 사용할 수 있다.
  • state는 render함수 밖에서 정의가 된다.
  • Hello World라는 문자를 직접 입력하는 것과
    변수에 값을 할당해서 출력하는 것은 굉장한 차이가 있다.
  • 결과는 같을지 몰라도 데이터의 재사용성, 값 수정의 용이성
    등등의 이유로 변수에 할당해서 필요할 때 가져가 쓰는 방법이
    훨씬 효율적인고 합리적이다.
  • this는 상위 scope를 가리킨다. (자바스크립트 문법)
import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';

class App extends Component {

  state = 
  {
    sampleText: 'Hello World....!!'
  }

  render() {
    return (
      <View style={styles.background}>
        <Text>{this.state.sampleText}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  background: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

728x90
반응형
LIST