리액트/컴포넌트

ch05.클래스형 컴포넌트의 State(1)

webmaster 2021. 7. 25. 21:44
728x90

클래스형 컴포넌트의 State

  • 컴포넌트에 State를 설정할 때는 constructor 메서드를 작성하여 설정한다.
    • 반드시 super(props)를 호출해야 한다.
    • 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수를 호출해 준다.
    • 그 후, this.state = { ... }로 값을 세팅해 준다
    • 컴포넌트의 state는 객체 형식이어야 한다.
    • render 함수에서 현재 state를 조회할 때는 this.state를 조회하면 된다.
    • button안에 props로 onClick을 넣었는데 이를 이벤트라고 한다.
    • 함수 내부에서는 this.setState라는 함수를 사용해서 state값을 바꿔준다.
    • Counter 컴포넌트를 App에서 불러와 렌더링 한다.
    • Counter.js
      •  
      • 넣을 수 from "react"; class Counter extends Component { constructor(props) { //컴포넌트에 state설정 할떄 사용하는 메소드 //컴포넌트 생성자 메소드로서 클래스형 컴포넌트에서 위 메소드를 호출시 반드시 super(props)를 호출하여야 한다. super(props); //이 함수를 호출시 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수를 호출한다 //state 초깃값 설정 this.state = { //state는 객체형식이어야 한다. number: 0, }; } render() { const { number } = this.state; //state를 조회할떄는 this.state로 조회 return ( <div> <h1>{number}</h1> <button //onclick을 통해 버튼이 클릭되었을떄 호출할 함수를 지정 //이벤트 설정 onClick={() => { //this.setState를 사용하여 state에 새로운 값 넣을수 있다 this.setState({ number: number + 1 }); }} > +1 </button> </div> ); } } export default Counter;
    • App.js
      • import React from "react";
        import Counter from "./Counter";
        const App = () => {
          return <Counter />;
        };
        export default App;
    • 결과
      • 실행 결과

State 객체 안에 여러 값이 존재할 경우

  • State 객체 안에는 여러 값이 존재할 수 있다. 
  • this.setState() 메서드를 호출할 때 값을 변경하지 않을 것이다
    • 인자로는 전달되는 개체 내부에 넣어 주지 않은 것 일 뿐이다.
  • import React, { Component } from "react";
    class Counter extends Component {
      constructor(props) {
        super(props);
        this.state = {
          number: 0,
          fixedNumber: 0,
        };
      }
      render() {
        const { number, fixedNumber } = this.state;
        return (
          <div>
            <h1>{number}</h1>
            <h2>바뀌지 않는 값 : {fixedNumber}</h2>
            {/*
             *   버튼이 클릭될떄 fixedNumber값 변경 x =>this.setState에서 인자로 fixedNumber는 넣지 않았다..
             *   this.setState 함수는 인자로 전달된 객체만 변경
             */}
            <button
              onClick={() => {
                this.setState({ number: number + 1 });
              }}
            >
              +1
            </button>
          </div>
        );
      }
    }
    export default Counter;
  • 실행결과
728x90

'리액트 > 컴포넌트' 카테고리의 다른 글

ch07.함수형 컴포넌트에서 UseState 사용하기  (0) 2021.07.25
ch06.클래스형 컴포넌트의 State(2)  (0) 2021.07.25
ch04. State종류  (0) 2021.07.25
ch03.Props(2)  (0) 2021.07.23
ch02. Props(1)  (0) 2021.07.22