개인 공부를 위해 작성했습니다
state : 상태
화면에 보여줄 컴포넌트의 UI 정보(상태)를 지니고 있는 객체
State
객체- `constructor()` 에 위치. `constructor()`는 페이지가 렌더될 때 초기화되는 값들
constructor() {
super();
this.state = {
color: 'red',
};
}
<h1 style={{ color: this.state.color }} >Class Component | State</h1>
// this : 해당 컴포넌트
// this.state : 해당 컴포넌트의 state 객체
// this.state.color : state 객체의 특정 key(color)값. 즉 "red"
setState()
constructor()
에서 선언된 state의 값을 변경할 때 사용import React, { Component } from 'react';
class State extends Component {
constructor() {
super();
this.state = {
color: 'red',
};
}
// `handleColor`함수를 호출할 때 state의 값을 변경하겠다 = setState
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;
props : properties(속성)
props는 부모 component로부터 전달 받은 데이터를 지니고 있는 객체
<Child titleColor={this.state.color}/>
titleColor
라는 Attribute를 임의로 지정하여 state
객체의 color
값을 전달// Parent.js
import React from 'react';
import Child from '../pages/Children/Children';
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;
{color : this.props.titleColor}
전달받은 props
객체의 titleColor
값// Child.js
import React from 'react';
class Child extends React.Component {
render() {
// console.log(this.props); 부모로 부터 전달받은 props값 확인
return (
<div>
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
// this : 해당 컴포넌트
// this.props : 해당 컴포넌트의 props 객체
// this.props.titleColor : props 객체의 특정 key(titleColor)값. 즉 "red"
</div>
);
}
}
export default State;
Props & event
state
는 titleColor
라는 Attribute를 통해 전달handleColor
메서드는 changeColor
라는 Attribute를 통해 전달// 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;
h1
의 스타일링에서 사용 style={{color : this.props.titleColor}}
button
의 onClick
이벤트 발생시 함수 호출 onClick= this.props.changeColor}
// 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;
✅ 목표!
부모 state
- 자식의 props
- 자식 component
어떻게 연결되는지 명확히 이해한다