본문 바로가기
💎 리액트

리액트 Component, render,constructor(props), props와 state 차이점

by 비타민찌 2022. 2. 12.
728x90

 

React 리액트

Component, render, constructor(props), props와 state 차이점

 

 

 

1. Component

Component란, 코드 뭉치를 다른 부분에 이식하거나 재사용하기 위해 사용하는 코드 블록 단위다.

Component를 파일 단위로 작성한 후, 필요한 위치에서 import로 사용할 수 있다.

(클래스형 component와 함수형 component가 있지만, 일단은 클래스형에 대해서만 다룬다. )

 

Component를 작성해보자.

좌측 탭에서 src 안에 이렇게 여러가지가 있는데,

우선 여기 src에 components 라는 이름의 폴더를 생성한다.

 

 

 

여기에 TestComponent1.js 라는 이름의 파일을 만들어 아래와 같이 입력한다.

import React, { Component } from "react";

class TestComponent1 extends Component {
  render() {
    return <h2>import: TestComponent1</h2>;
  }
}
export default TestComponent1;
 

 

첫 번째 줄에서 import한 Component를 상속받아서, TestComponent1 클래스에서 사용하는 코드다.

class TestComponent1 extends Component
 
 

2. render

render는 리액트에서 component의 생성, 변경, 소멸 과정을 뜻하는 생명주기 함수다.

render()는 return되는 html 형식의 코드를 화면에 그려주는 함수다. 화면 내용이 변경되어야 할 시점에 자동으로 호출된다.

render() {
    return <h2>import: TestComponent1</h2>;
  }
 

이제 코드를 저장하고, App.js 파일을 수정해주자.

 

App.js

import React from "react";
import TestComponent1 from "./components/TestComponent1";

function App() {
  return (
    <div>
      <h1>App.js</h1>
      <TestComponent1></TestComponent1>
    </div>
  );
}

export default App;
 

import TestComponent1 from "./components/TestComponent1"로 컴포넌트를 import 해주고,

아래 return 함수에서 TestComponent1 컴포넌트를 사용한다.

여기까지 작성 후 control+s 키로 파일을 저장하면, 크롬 웹 브라우저에서 아래와 같은 창이 뜰 것이다.

 

TestComponent1이 잘 적용되었다.

계속해서 TestComponent1.js에 constructor(props) 함수를 적용해보자.

 

3. constructor(props)

TestComponent1 클래스 안에 다음 코드를 작성한다.

import React, { Component } from "react";

class TestComponent1 extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    console.log("constructor call!");
  }

  render() {
    return <h2>import: TestComponent1</h2>;
  }
}
export default TestComponent1;
 

저장 후 새로고침을 누르고 페이지 콘솔창을 보면 로그를 확인할 수 있다.

 

코드를 살펴보자.

  constructor(props) {
    super(props);
    this.state = {};
    console.log("constructor call!");
  }
 

constructor(props) 함수는, 생명주기 함수 중 가장 먼저 실행되며 처음 한 번만 호출된다.

component 내부에서 사용되는 변수 state를 선언하고,

부모 객체에서 전달받은 변수 props를 초기화할 때 사용한다. state와 props란 무엇일까?

 

 

4. props vs state 차이점

props

리액트의 props란, 컴포넌트끼리 값을 전달하는 수단이다.

HTML 태그의 속성처럼, 한 컴포넌트의 요소에 props value를 지정하면

다른 컴포넌트에서 그 value에 값을 넣어 사용할 수 있다.

 

state

State는 props처럼 App 컴포넌트의 렌더링 결과물에 영향을 주는 데이터를 갖고 있는 객체지만,

props는 (함수 매개변수처럼) 컴포넌트에 전달되는 반면,

state는 (함수 내에 선언된 변수처럼) 컴포넌트 안에서 관리된다는 차이가 있다.

 

props를 사용했는데도 state를 사용하는 이유는

사용하는 쪽과 구현하는 쪽을 철저하게 분리시켜서 양쪽의 편의성 살리기 위해서이다.

 

State 객체를 사용하고 싶다면, 컴포넌트를 생성할 때 가장 윗부분(render() 함수보다 먼저)에 constructor() 함수를 적어준다. 컴포넌트 생성자에서 super를 호출하기 전에는 this를 사용할 수 없기 때문이다.

 

* super는 자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는 데 사용하는 참조 변수.

즉, 조상 클래스의 생성자를 호출한다.

* 조상의 멤버와 자신의 멤버를 구별하는 데 사용되다는 점을 제외하고는 super와 this는 근본적으로 같다.

  constructor(props) {
    super(props);
    this.state = {};
    console.log("constructor call!");
  }
 

 

 

이번 포스팅의

Component, render(), constructor(props),

props와 state는 정말 중요한 개념이기 때문에 잘 알아두는 것이 좋다.

728x90

댓글