■ 프로그래밍/React
Props, State, constructor()
hi_mj
2020. 4. 14. 00:21
Props는 컴포넌트를 사용하는 부모에서 자식으로 전달하여 사용하고,
State는 컴포넌트 내부에 존재하여 상태값을 변경한다.
Props | State |
읽기 전용(read-only) | 비동기 가능 |
수정할 수 없음 | this.setState()로 값 변경 가능 |
상위에서 하위로 props 전달 | 하위에서 상위로 event를 통해 값 전달 |
모두 Object이며 화면에 보여줄 정보(상태)를 갖고 있음 | |
Props, State 값이 바뀌면 reder()가 자동으로 호출 |
consturctor() (생성자 함수)
- class의 instance가 생성될 때 항상 호출되는 함수
- 사용할 목적이 없다면 작성하지 않아도 됨
- this.props의 정의를 위해 super(props) 호출 필수
- 초기화 할 값들을 this.state안에 넣어 세팅해 줌
- 최초 컴포넌트가 mount(생성) 되기 전에 실행
import React, {Component} from 'react';
class Hello extends Component {
constructor(props) {
super(props);
this.state = {
name: 'kmj', // 초기화 할 값 설정
}
}
render() {
return (
<div>Hello {this.state.name}</div>
);
}
}
export default Hello