props는 부모 컴포넌트가 자식 컴포넌트에게 주는 값. 자식 컴포넌트에서는 props를 받아오기만하고, 받아온 props를 직접 수정 할 수는 없다.
state는 컴포넌트 내부에서 선언하며 내부에서 값을 변경 할 수 있습니다.
- state는 단어 뜻 그대로 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값입니다.
- state는 화면에 보여줄 컴포넌트의 UI 정보(상태)를 지니고 있는 객체입니다.
- state는 컴포넌트 내에서 정의하고 사용하며 얼마든지 데이터(객체)가 변경될 수 있다.
state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔 때 마다 리액트가 자동적으로 우리가 구현한 render 함수를 호출하며 효율적으로 화면 (UI)에 나타내기 위함이다.
📍 클라스 컴포넌트 | state
import React from 'react';
class State extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1>Class Component | State</h1>
</div>
);
}
}
export default State;
render
함수가 필요하고 화면에 나타내고 싶은 JSX 요소가 return
문 안에 들어있습니다.constructor
함수를 작성하여 설정합니다.super()
를 호출합니다.this.state
값에 컴포넌트의 초기 상태값을 설정해 주었습니다.📍 state 객체
this.state = {
color: 'red'
};
color
key의 값으로 "red"
를 value로 지정하겠습니다.📍 state 사용 예시
return
문 안에 <h1>
타이틀 요소가 있습니다.<h1 style={{ color : }}>Class Component | State</h1>
<h1 style={{ color: this.state.color }}>Class Component | State</h1>
// this : 해당 컴포넌트
// this.state : 해당 컴포넌트의 state 객체
// this.state.color : state 객체의 특정 key(color)값. 즉 "red"
import React, { Component } from 'react';
class State extends Component {
constructor() {
super();
this.state = {
color: 'red',
};
}
handleColor = () => {
this.setState({
color: 'blue'
})
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Class Component | State</h1>
<button onClick={this.handleColor}>Click</button>
</div>
);
}
}
export default State;
<h1>
태그 아래에 <button>
요소를 추가해주었습니다.<button>
요소에서 onClick
이벤트 발생this.handleColor
, 즉 현재 컴포넌트(State
)의 handleColor
함수 실행handleColor
함수 실행 시 setState
함수 실행 - state의 color
값을 'blue'
로 변경render
함수 호출<h1>
태그 글자 색상 변경
- props는 단어 뜻 그대로 컴포넌트의 속성값입니다.
- props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체입니다.
- props를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값, event handler를 넘겨줄 수 있습니다.
부모 컴포넌트가 있고, 자식 컴포넌트로 분리 해줄 때만 props 객체가 필요합니다!
컴포넌트 안에서 자체적으로 데이터를 정의해서 사용하는 state와는 다르게, props는 컴포넌트 외부에서 데이터를 제공받는다. 가장 근본적인 이유는 컴포넌트의 재사용을 높이기 위해서이다. 상황에 따라 주어진 데이터를 받아서 그 테이터에 맞게 UI를 보여주기 위해서 사용 되어진다.
📍 부모 컴포넌트
import React from 'react';
import Child from '../pages/Child/Child';
class Parent extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1>Parent Component</h1>
<Child />
</div>
);
}
}
export default State;
<Child />
컴포넌트를 import 후 <h1>
태그 아래에 위치해주었습니다.<Child />
컴포넌트에게 props를 통해 넘겨보도록 하겠습니다.import React from 'react';
import Child from '../pages/Child/Child';
class Parent extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1>Parent Component</h1>
<Child titleColor={this.state.color} />
</div>
);
}
}
export default State;
titleColor
속성을 생성해주었습니다.titleColor
의 값으로 this.state.color
, 즉 부모 컴포넌트의 state 객체 중 color
값을 전달해주었습니다.<Child />
컴포넌트 내부에서 전달 받은 props 데이터를 어떻게 사용하는지 확인해보겠습니다.📍 자식 컴포넌트
import React from 'react';
class Child extends React.Component {
render() {
// console.log(this.props);
return (
<div>
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
</div>
);
}
}
export default State;
<Child />
컴포넌트 내부에 <h1>
태그가 있습니다.render
함수와 return
함수 사이에서 this.props
값을 console.log
로 확인합니다.<h1 style={{color : this.props.titleColor}}>Child Component</h1> // this : 해당 컴포넌트 // this.props : 해당 컴포넌트의 props 객체 // this.props.titleColor : props 객체의 특정 key(titleColor)값. 즉 'red'
props를 통한 event handler
// Parent.js
import React from 'react';
import Child from '../pages/Children/Children';
class Parent extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
handleColor = () => {
this.setState({
color: 'blue'
})
}
render() {
return (
<div>
<h1>Parent Component</h1>
<Child titleColor={this.state.color} changeColor={this.handleColor}/>
</div>
);
}
}
export default State;
changeColor
값으로 Parent 함수에서 정의한 handleColor
함수 자체를 넘겨주고 있습니다.handleColor
함수를 활용하는지 살펴보겠습니다.// Child.js
import React from 'react';
class Child extends React.Component {
render() {
// console.log(this.props);
return (
<div>
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
<button onClick={this.props.changeColor}>Click</button>
</div>
);
}
}
export default State;
<Child />
컴포넌트 내부에 <button>
태그가 있습니다.<button>
요소에서 onClick
이벤트 발생this.props.changeColor
실행changeColor
, 즉 부모 컴포넌트로부터 전달받은 handleColor
함수 실행handleColor
함수 실행 시 setState
함수 호출 - state의 color
값을 'blue'
로 변경render
함수 호출<Child />
컴포넌트에 변경된 state 데이터 (this.state.color
) 전달this.props.titleColor
를 글자 색상으로 지정하는 <h1>
타이틀 색상 변경