- state : 상태
- 단어 뜻 그대로 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값입니다.
- state는 화면에 보여줄 컴포넌트의 정보(상태)를 지니고 있는 객체입니다.
- 객체 그 자체.
- state는 컴포넌트 내에서 정의하고 사용하며 얼마든지 데이터(객체)가 변경될 수 있습니다.
- constructor는 state를 감싸고 있는 구조일 뿐이다.
- props : properties(속성)
- 단어 뜻 그대로 컴포넌트의 속성값입니다.
- props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체입니다.
- props를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값, event handler를 넘겨줄 수 있습니다.
- 부모가 자식에게 상속하는 속성
App.js
import React from 'react';
class State extends React.Component {
constructor() {
super();
this.state = {
color : 'red'
};
}
render() {
return (
<div>
<input style={{color : this.state.color}} type="text" value="id">
</input>
<button>로그인</button>
</div>
);
}
}
export default State;
: constructor에서 지정한 state 상태 속성{ color }을 render 함수의 input의 value 값에 접근하여 inline style로 받아왔다.
<input style=
{{color : this.state.color}}
type="text" value="id”>
// this : 해당 컴포넌트
// this.state : 해당 컴포넌트의 state 객체
// this.state.color : state 객체의 특정 key(color)값.
즉 "red" State(객체 그 자체)의 객체 속성을 이용하여 객체 key 값에 접근하듯이 style를 적용한 것을 알 수 있다!
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import State from './App';
ReactDOM.render(<State />,
document.getElementById('root'));
State에서 상태값을 설정하는 이유는 결국 component 안의 요소에서 그 상태값을 반영해서 화면(UI)애 나타내기 위함이다.
두개의 state에 접근하여 inline style로 둘다 적용시켜보자.
import React from 'react';
class State extends React.Component {
constructor() {
super();
this.state = {
color1 : ‘red’,
color2 : 'white’,
backgroundColor : 'blue'
};
}
render() {
return (
<div>
<input
style={{color : this.state.color1}}
type="text" value="id">
</input>
<button
style={{backgroundColor : this.state.backgroundColor,
color : this.state.color2}}>
로그인</button>
</div>
);
}
}
export default State;
: 두가지 state 상태값을 button 내의 inline style로 적용시킬 때,
{ { style1 : state1 , style2: state2 } }
안에서 객체를 작성하듯이 ‘ , ‘로 분류하여 작성하면 적용되는 것을 확인할 수 있다.