16일차

Grace·2021년 11월 23일
0

코드캠프 TIL

목록 보기
17/34

컴포넌트 생명주기

render

그리기

componentDidMount

그리고 난 뒤

componentDidUpdate

그리고 난 후 변경됐을 때

componentDidUnmount

그리고 난 뒤 사라질 때

클래스 컴포넌트

컴포넌트를 만드는 설명서
클래스 안에 있는 함수들은 메서드라고 부른다.

component, createRef, Router 를 사용하기 위해 import

import { Component, createRef } from "react";
import Router from "next/router";

타입스크립트이므로 count 에 number를 설정

interface IState {
  count: number;
}

Component 클래스형 컴포넌트라 옛방식들이다.

export default class ClassComponentLifecyclePage extends Component {
  inputRef = createRef<HTMLInputElement>();
  state = {
    count: 0,
  };
componentDidMount = () => {
    console.log("컴포넌트 마운트 완료!!");
    this.inputRef.current.focus(); 
  };
componentDidUpdate = () => {
    console.log("컴포넌트 수정 완료!!");
  };
componentWillUnmount = () => {
    console.log("잘가요~~");
  };
onClickCount = () => {
    this.setState((prev: IState) => ({
      count: prev.count + 1,
    }));
  };
onClickMove = () => {
    Router.push("/");
  };
render() {
    return (
      <>
        현재카운트 : {this.state.count}
        <button onClick={this.onClickCount}>카운트 증가!!!</button>
        <button onClick={this.onClickMove}> 페이지 이동하기 </button>
        <input type="text" ref={this.inputRef} />
      </>
    );
  }
}

this

클래스나 객체에 포함되지 않으면 기본적으로 window를 지칭한다.

클래스 연산자에서 함수(메서드)를 연결해줄 경우 onClick={this.onClickCounter.bind(this)} 이런 식으로 bind를 걸어주어야한다.

함수형 컴포넌트

useEffect, useRef, useState, useRouter를 쓰기위해 import

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";

const

export default function FunctioanlComponentLifecyclePage() {
  const router = useRouter();
  const [count, setCount] = useState(0);
  const inputRef = useRef<HTMLInputElement>();

componentDidMount 와 동일

useEffect(() => {
  console.log("컴포넌트 마운트 완료!!");
  inputRef.current.focus();
componentWillUnmount 와 동일
    return () => {
      console.log("잘가요~~");
    };
  }, []);

componentDidUpdate 와 동일

  useEffect(() => {
    console.log("컴포넌트 수정 완료!!");
  });

####함수선언 및 return

   function onClickCount() {
    setCount((prev) => prev + 1);
  }
  function onClickMove() {
    router.push("/");
  }
  return (
    <>
      현재카운트 : {count}
      <button onClick={onClickCount}>카운트증가!!</button>
      <button onClick={onClickMove}>페이지이동</button>
      <input type="text" ref={inputRef} />
    </>
  );
 }
profile
기술블로그 이전:: https://meercat.tistory.com/

0개의 댓글