HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
📝
프로젝트 노트
/
TS로 웹 컴포넌트 만들기
TS로 웹 컴포넌트 만들기
TS로 웹 컴포넌트 만들기

TS로 웹 컴포넌트 만들기

Tags
Typescript
Javascript
Status
Archived

들어가며

  • 현 시점의 웹 어플리케이션은 컴포넌트 단위로 설계되고 개발된다.
  • 컴포넌트마다 컴포넌트를 렌더링할 때 필요한 상태를 관리한다.
  • 상태 관리의 핵심은 다음과 같다.
    • state가 변경되면 render를 실행한다.
    • state는 setState로만 변경해야 한다.
 

구현

export default abstract class Component<P = {}, S = {}> { protected $target: HTMLElement; protected props?: P; protected state?: S; private isMounted: boolean; constructor($target: HTMLElement, props?: P, state?: S) { this.isMounted = false; this.$target = $target; this.props = props; this.state = state; this.componentInit(); this.render(); this.isMounted = true; } protected componentInit() {} protected componentDidMount() {} protected componentDidUpdate() {} protected setState(newState: S) {} protected getInnerHTML() { return ""; } protected render() { this.$target.innerHTML = this.getInnerHTML(); if (this.isMounted) { this.componentDidUpdate(); } else { this.componentDidMount(); } } }
 

핵심 개념

 
class component
  • Class는 객체를 생성하기 위한 템플릿이다.
  • 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화한다.
  • extends 키워드는 다른 클래스의 자식 클래스를 생성하기 위해 사용된다(상속).
 
abstract
  • 추상 클래스를 사용한 이유는 자식 클래스에서 추상 메소드를 반드시 구현하도록 강요하기 위해서이다(라이프 사이클).
  • Component.ts는 자식 클래스에 오버라이딩 하기 위함이다.
 
constructor
  • constructor 메서드는 클래스의 인스턴스 객체를 생성하고 초기화하는 특별한 메서드이다.
  • isMounted란 변수를 false로 지정하였다 render가 끝나고 true로 지정하면 render 됐을 때 처음 mount가 되는 건지 update가 되는 건지를 구별할 수 있다.
 
 
 
참고자료
Vanilla Javascript로 웹 컴포넌트 만들기
Classes