본 포스팅의 관련 예제는 아래 github 참고
https://github.com/action-intent/ReactNative/tree/master/StateProps
State(mutable)
- React에서 데이터를 만들고 다루는 방식
- Component가 생성될때 선언
- setState 함수 내에서 갱신
State를 정의하고 이벤트를 받아 갱신해보는 예제를 실행해 봅시다.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class MyComponent extends Component {
constructor(){ // 1. 생성자에서 State 선언 및 초기화
super()
this.state = {
year: 2018
}
}
updateYear() { // 2. render() 위에 사용자 정의 함수
this.setState({ // * this.sate.year = 2019 처럼 직접 갱신하지 않는다.
year: 2019
})
}
render() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text onPress={() => this.updateYear()}> // 3. Text 터치 시 updateYear 함수 호출
The year is: { this.state.year }
</Text>
</View>
);
}
}
* state를 직접 수정하면 render()가 호출되지 않아 갱신되지 않습니다. 대신 this.forceUpdate()를 통해 강제 호출하는 방법이 있습니다.
실행하면 다음과 같이 텍스트가 나타나며 클릭 시 2019로 변경
Props(immutable)
- Component 파라미터로 전달 됨(부모에서 자식으로 전달)
- Component 내에서 갱신되지 않음
Props를 이해하기 위한 코드 예제
* const를 사용하여 this.state, this.props 등 반복코드를 제거한 것을 참고(네이밍 통일)
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class LotsOfGreetings extends Component { //부모 Component export
constructor(){
super()
this.state = {
username: 'Rexxar'
}
}
updateName(){
this.setState({ username: 'Jaina'})
}
render() { //name과 updateName을 props로 전달
const { username } = this.state
return (
<View style={{alignItems: 'center', top: 50}}>
<Greeting
updateName={ () => this.updateName() }
name= { username } />
</View>
);
}
}
class Greeting extends Component { //자식 Component : props를 쓴다.
render() {
const { name, updateName } = this.props //props를
return (
<View style={{alignItems: 'center'}}>
<Text onPress={ updateName }> Hello {name}!</Text>
</View>
);
}
}
조금 복잡해 보일 수 있으나 결국 LotsOfGreetings에서 정의한 state를 Greeting에 props로 전달하여 사용할 수 있도록 하는 과정
왼쪽과 같은 결과 화면과 텍스트를 눌렀을때 이름이 업데이트 됨
Stateless component props(함수형 component)
기존 class 정의 형태에서 const Greeting = (props) => { ... } 형태로 코드를 간결하고 재사용성을 높일 수 있다.
배열 개체 받기
배열 형태의 props는 아래와 같은 형태로 핸들링 할 수 있다.
let topics = props.topics.map((topic, i) => {
return <Text>{ topic }</Text>
})
생명주기 메서드
Component의 특정 주기(생성, 갱신, 파기)에 자동으로 호출되는 메서드
- getDerivedStateFromProps : props가 변경되어 갱신 시 호출
- componentDidMount : Component가 로딩되고 바로 한번
- shouldComponentUpdate : 새로운 state, props로 render의 호출 여부를 결정
- componentDidUpdate : Component가 재 렌더링 된 후 한번 호출(이전 state, props)
- componentWillUpdate : Component가 파기되기 전에 호출(리스너, 타이머 정리)
예제 코드를 통해서 React native의 주요 요소에 대해서 이해?했으나 한번 봐서는 난해하긴 마찬가지 입니다. 젠장..
이해가 될때까지 위 내용은 숙지를 하시고 다음 포스팅에서는 예제 앱을 만들어 보겠습니다.
'React native' 카테고리의 다른 글
Todo 2 (0) | 2019.12.25 |
---|---|
Todo 1 (0) | 2019.12.25 |
Project 생성 및 빌드 (0) | 2019.12.25 |
React native intro (0) | 2019.12.25 |
첫 애플리케이션 만들기 (0) | 2019.04.14 |