리액트에서 state란 단어의 뜻처럼 컴포넌트 내부의 상태를 지니고 있는 객체이다. state는 컴포넌트 내에서 정의하고 사용하며 얼마든지 데이터를 변경할 수 있다.
import React from 'react';
class State extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>
State
</h1>
</div>
);
}
}
export default State;
React 에서 이벤트를 처리하는 방식은 DOM 에서 이벤트를 처리하는 방식과 매우 유사하지만 차이점이 있다.
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
form 태그에서 'onSubmit' 이벤트가 발생하면 handleSubmit 함수가 실행된다.
state 의 값을 변경하고 싶다면 setState 라는 함수를 통해서 변경해야 한다.
import React, { Component } from 'react';
class State extends Component {
constructor() {
super();
this.state = {
isRed: true,
};
}
handleColor = () => {
this.setState({
isRed: !this.state.isRed
})
}
render() {
return (
<div>
<h1 className={isRed ? "red" : "blue"}>State</h1>
<button onClick={this.handleColor}>Click</button>
</div>
);
}
}
export default State;
코드가 실행되는 순서
<button>
요소에서 onClick
이벤트 발생this.handleColor
, 즉 현재 컴포넌트(State
)의 handleColor
함수 실행handleColor
함수 실행 시 setState
함수 실행 - state의 isRed
값을 'false'
로 변경render
함수 호출<h1>
태그 글자 색상 변경부모가 자식에게 부모의 state를 변화시키는 event handler 함수를 props로 넘겨준다면, 자식은 그 함수를 실행하여 부모의 state를 변화시킬 수 있다.
// Parent.js
import React from 'react';
import Child from '../pages/Children/Children';
class Parent extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
changeColor = () => {
this.setState({
color: 'blue'
})
}
render() {
return (
<div>
<h1>Parent Component</h1>
<Child titleColor={this.state.color} changeColor={this.changeColor}/>
</div>
);
}
}
export default State;
// Child.js
import React from 'react';
class Child extends React.Component {
render() {
return (
<div>
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
<button onClick={this.props.changeColor}>Click</button>
</div>
);
}
}
export default State;
코드가 실행되는 순서
<button>
요소에서 onClick
이벤트 발생this.props.changeColor
실행changeColor
함수 실행changeColor
함수 실행 시 setState
함수 호출 -> state의 color
값을 'blue'
로 변경render
함수 호출<Child />
컴포넌트에 변경된 state 데이터 전달(this.state.color
)this.props.titleColor
으로 자식 컴포넌트에게 전달되고 <h1>
색상 변경https://ko.reactjs.org/docs/state-and-lifecycle.html
https://ko.reactjs.org/docs/handling-events.html
https://yeri-kim.github.io/posts/react-state/
https://yeri-kim.github.io/posts/react-event/