State
state
를 사용하기 위한 초기 틀 (class와 render 사이에 들어간다)
constructor () {
super ();
this.state = {상태 들어가는 곳};
}
setState
를 활용하여 state를 바꿀 수 있다. (함수는 꼭 arrow 함수로 써야 this와 관련된 error를 피할 수 있다.)
changeState = () => {
this.setState({
titleColor: ‘red’
});
};
Props
모든 component가 갖고 있는 내장 객체
부모에서 자식으로 넘겨주는 속성이다. 자식에서는 속성으로 바꿀 수 없고 읽을 수만 있다.
component는 어떤한 속성이라도 받아줄 수 있다. (String, number, boolean, array, function 등 JS로 가능한 모든 것)
부모에서 state와 props를 통해 자식 컴포넌트로 props 속성값을 전달해서 사용할 수 있다.
// 부모 요소
{productList.map((product, idx) => {
return (
<EachProduct
key={idx}
name={product.name}
/>
);
})}
//자녀 컴포넌트
<h3>
<div>{this.props.name}</div>
</h3>
구조 분해 할당하기!
state와 props를 계속 사용하다보면 this.state.name
, this.props.name
이런식으로 계속 앞에 중복되게 적게 된다. 그러면 가독성도 떨어지고 유지보수하기 힘들어진다. 그래서 조금 더 간편하게 만들기 위해서 구조 분해 할당을 해준다.
// 원래는 이렇게 적겠지만 구조분해할당을 하게 되면 아래와 같이 적을 수 있다.
<div> {this.state.name} </div>
<div> {this.props.name} </div>
// 구조분해할당 후
const {name} = this.state
const {name} = this.props
<div> {name} </div>