본문 바로가기
React

[React] Component 에서 State 사용하기-떽떽대는 개발공부

by 떽이 2021. 1. 1.

2020/12/31 - [React] - [React] Component 에서 props 사용하기

 

[React] Component 에서 props 사용하기

2020/12/31 - [React] - [React] Component 생성하고 모듈화하기 [React] Component 생성하고 모듈화하기 2020/12/30 - [React] - [React] 프로젝트 생성하고 실행하기 Component 생성 및 모듈화 이전 글에서 프로..

ddeck.tistory.com

 

 

 

Component 에서 State 사용하기

컴포넌트에서 유동적인 데이터를 다룰 때, state 를 사용한다.

React.js 어플리케이션을 만들 땐, state를 사용하는 컴포넌트의 갯수를 최소화 해야한다.

예를들어, 10 개의 컴포넌트에서 유동적인 데이터를 사용 하게 될 땐, 각 데이터에 state를 사용 할 게 아니라, props 를 사용하고 10 개의 컴포넌트를 포함시키는 container 컴포넌트를 사용하는것이 효율적이다.

사용법

src/components/Example.js

import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Example Header state",
content: "Example Content State"
};
}
updateHeader(text){
this.setState({
header: "Example Header has changed"
});
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
<button onClick={this.updateHeader.bind(this)}>Update</button>
</div>
);
}
}
export default Example;

 

  • state 의 초기 값을 설정 할 때는 constructor(생성자) 메소드에서 this.state= { } 를 통하여 설정한다.
  • state 를 렌더링 할 때는 { this.state.stateName } 을 사용한다.
  • state 를 업데이트 할 때는 this.setState() 메소드를 사용한다. ES6 class에선 auto binding이 되지 않으므로, setState 메소드를 사용 하게 될 메소드를 bind 해주어야 한다. (bind 하지 않으면 React Component 가 가지고있는 멤버 함수 및 객체에 접근 할 수 없다.)

 

적용하기

src/components/Example2.js

import React from 'react';
class Example2 extends React.Component {
constructor(props){
super(props);
this.updateNumber = this.updateNumber.bind(this);
}
updateNumber(){
this.props.onUpdate();
}
render(){
return (
<div>
<h1>number: { this.props.number }</h1>
<button onClick={this.updateNumber}>click</button>
</div>
);
}
}
export default Example2;

 

기본값을 나타내는 h1 element와, 클릭 하면 1씩 더하는 button element를 렌더링 한다.

이 컴포넌트에서는 두가지 prop을 사용한다.

  1. number: 기본 값
  2. onUpdate: function 형태의 prop 으로서, parent 컴포넌트에 정의된 메소드를 실행 할 수 있게 한다.

이제, parent 컴포넌트인 App 컴포넌트에서 RandomNumber 컴포넌트를 사용한다.

 

src/components/App.js

import React from 'react';
import Example2 from './Example2';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
value: 0
};
this.updateValue = this.updateValue.bind(this);
}
updateValue(){
let number = this.state.value;
let plusNumber = number + 1;
this.setState({
value: plusNumber
});
}
render(){
return (
<div>
<Example2 number={this.state.value}
onUpdate={this.updateValue} />
</div>
);
}
}
export default App;

 

출력물

클릭 할때마다 숫자가 1씩 더해진다.

 

 

댓글