๊ฐ์ธ ๊ณต๋ถ๋ฅผ ์ํด ์์ฑํ์ต๋๋ค
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 & eventstate๋ 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 ์ด๋ป๊ฒ ์ฐ๊ฒฐ๋๋์ง ๋ช
ํํ ์ดํดํ๋ค