React JS

React 컴포넌트를 class로 정의

수연 (Suyeon) 2022. 2. 13. 13:57
반응형

React 컴포넌트 class 정의할 때 

- class 형 컴포넌트를 만드는 이유는 'state를 사용하기 위함' 입니다.

- React.Component를 상속받아야만 합니다.

- React.Component 클래스는 약 500줄이 넘는 코드를 가지고 있습니다.

- 이때 App 컴포넌트는 클래스이므로 함수가 아니라서 return 사용이 불가능 합니다.

- 따라서 render() 함수를 사용해서 JSX를 반환합니다.

class App extends React.Component {
  render() {
    return <h1>컴포넌트</h1>;
  }
}

 

render() 함수를 구현하지 않아도 사용할 수 있는 이유

- React.Component를 상속받았기 때문입니다.


 

state

- 객체 형태의 데이터입니다.

- class component 안에 소문자를 이용해서 state = {}로 사용하면 됩니다.

- state의 값을 출력할 때는 render() 안에 {this.state.count} 하면 됩니다.

class App extends React.Component {
  state = {
    count: 0    //이름: 값
  }
  render(){
    {this.state.count}  //0
  }
}

 

버튼으로 state 값 변경하기

- 함수를 만들고 해당 태그에 onClick = {this.함수명}을 사용합니다. 이때 함수명 뒤에 ()를 붙이면 안됩니다.

- 먼저 state를 직접 변경하는 예제를 해봅니다.

class App extends React.Component {
  state = {
    count: 0
  };
  change = () => {
    this.state.count = 1;
  };
  
  render() {
    return (
      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.change}>Change</button>
      </div>
    );
  }
}

- 이러면 아래와 같은 오류가 발생합니다.

   Do not mutate state directly.    →    state를 직접 변경하지 말라.

- React는 state를 직접 변경하지 못하게 하기 위해서 직접 state를 변경하면 render() 함수 다시 실행하지 않습니다.

- 이를 해결하기 위해서 setState()를 사용합니다.

class App extends React.Component {
  state = {
    count: 0
  };
  change = () => {
    this.setState({ count: this.state.count+1 });  //1씩 증가
  };
  
  render() {
    return (
      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.change}>Change</button>
      </div>
    );
  }
}

버튼 누르기 전

 

버튼 누른 후

 

※ setState()에 인자를 넣어서 사용하면 성능에 문제가 생길 수 있기에 함수로 넘겨주는 것이 효율적입니다.

class App extends React.Component {
  state = {
    count: 0
  };
  change = () => {
    this.setState(current => ({   //함수 사용
      count: current + 1
    }));
  };
  
  render() {
    return (
      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.change}>Change</button>
      </div>
    );
  }
}
728x90