H'academy
  • H'academy
  • Web
    • Back-end
      • Spring Framework
        • Spring 개발환경 구축
          • Project 생성
          • Maven 설정
          • Maven 저장소 위치 설정
          • Apache Tomcat 연동
          • Lombok 설정
        • Spring MVC Project
          • pom.xml
          • web.xml
          • root-context.xml
          • servlet-context.xml
          • DispatcherServlet
        • Controller
          • File Upload / Download
          • RestController(작성중)
        • Spring Test
          • Assert 단정문
          • Spring 환경 연동 테스트
          • MockMvc Test
        • Spring AOP
          • AOP 용어
          • Pointcut Expression
          • Filter
          • Interceptor
          • Filter vs Interceptor
          • Controller Advice(작성중)
        • Spring JDBC
          • DBCP
          • myBatis
            • ResultMap 활용
        • ETC
          • Logging
            • Tomcat Logging 설정
          • Property 관리
          • E-mail
            • Gmail 변경사항
          • Scheduler
          • Websocket
      • Spring Boot
        • STS 다운로드
        • 프로젝트 생성
        • 프로젝트 구조
        • Spring Devtools
        • Spring Controller
          • JSP 연동
            • * JSP 생성불가 문제
            • Spring Boot 3.x
          • Model
          • 요청 파라미터 처리
          • 경로 변수 처리
          • 요청 메소드
          • Redirect
          • Spring Actuator
        • Spring Boot JDBC
          • Database 정보
          • DAO Pattern
          • ORM Framework
            • myBatis
              • Mapper 생성
            • Spring Data JPA
        • Spring AOP
          • AspectJ
          • Filter
          • Interceptor
          • ControllerAdvice
        • REST API
        • Spring WebSocket
        • Send Mail
        • Logging
        • Spring Boot Test
        • Lombok
      • Java EE
        • 개발환경 구성
          • Server와 Client
          • Web Server와 WAS
        • Dynamic Web Project
      • Apache Tomcat
        • Apache Tomcat 구조
        • Tomcat User 생성
        • Tomcat Manager 설정
      • Maven
      • Jenkins
        • Installation
          • Github Webhook 설정
          • Maven 연동
        • Project setting
          • 소스 코드 관리 설정
          • 빌드 유발 설정
          • 빌드 작업 설정
      • OpenAPI(swagger)
        • swagger 2.x (legacy)
        • swagger 3.x (boot)
        • Swagger UI 꾸미기
        • SpringDoc
    • Front-end
      • HTML
        • Heading
        • <A>
        • <IMG>
        • <DIV>
        • <TABLE>
        • <FORM>
          • <INPUT>
          • <SELECT>
          • <TEXTAREA>
          • <FIELDSET>
        • List
      • CSS
        • CSS 적용 방식
          • 크기(size)
            • 픽셀(px)
          • 색상(color)
        • CSS 선택자
          • 스타일 우선순위
        • CSS 주요 속성
          • 크기 속성
            • border
            • margin
            • padding
            • box-sizing
          • 배경 속성
          • 글자 속성
            • font
            • text
          • 배치 속성
            • position
            • display
            • overflow
            • float
            • flexbox
        • CSS Reset
      • JS
        • syntax
          • let, const
          • 구조 분해 할당
          • spread operator
          • Object copy
          • this
          • module
        • jQuery
          • structure
          • function
          • ajax
            • ajax file upload
        • VueJS
          • CDN(Vue3)
            • 기본 구조
            • Vue Devtools
            • jQuery vs VueJS
            • Vue instance
              • data
                • IME issue
              • v-model
              • template
              • computed
              • watch
                • deep watch
                • vs Computed
              • methods
            • Vue directive
              • v-text
              • v-html
              • v-bind
                • v-bind style
                • v-bind class
              • v-on
                • once
                • prevent
              • v-show
              • v-if
              • v-for
          • Vue-cli 3
            • 프로젝트 구조
            • src
              • main.js
              • App.vue
              • HelloWorld.vue
            • Vue Router 4
              • History mode
              • 404 not found
              • Guard
                • beforeEach
            • Vuex
              • 이동 횟수 측정
            • axios
              • interceptor
          • Vue-electron
        • ReactJS
          • CDN(React18)
            • 템플릿 설명
            • JSX
            • render
            • Handling Events
              • onClick
              • onInput
            • Component
              • 클래스 컴포넌트
                • state
                • props
                • event
                  • Mouse
                  • Input
                • lifecycle
              • 함수형 컴포넌트
                • useState
                • useEffect
                • useReducer
                • useMemo
                • props
                • 조건부 렌더링
          • CRA
            • 자원 경로 설정
            • src 절대 경로 설정
            • react-router
            • Context API
            • Electron 설정
        • Webpack
          • NodeJS
          • Git
    • Ubuntu server
      • Jenkins
    • 테스트 도구
      • JMeter
        • Test Plan
        • Test Plan(with login)
        • Plugin 설치
    • WebRTC
  • Base Language
    • Java
      • Java 실행 과정
        • 개발 환경 구축
        • 샘플 코드 작성
        • 컴파일/실행
        • 환경 변수 설정
      • Java 초급
        • Hello world
        • 자료와 정보
        • 변수
          • 정수
            • 정수의 저장 원리
            • 정수형 변수 생성
          • 실수
            • 실수의 저장 원리
            • 실수형 변수 생성
          • 논리
            • 논리형 변수 생성
          • 문자
          • 문자열
            • 문자열 변수 생성
          • 사용자 정의 자료형
        • 연산자
          • 대입 연산
          • 부호 연산
          • 산술 연산
          • 복합 대입 연산
          • 증감 연산
          • 쉬프트 연산
          • 비트 연산
          • 비교 연산
          • 논리 연산
          • 삼항 연산
          • 변환 연산
        • 표준 입출력
          • 표준 출력
          • 표준 오류 출력
          • 표준 입력
            • Scanner 입력
        • 제어문
          • if 구문
            • 단일 조건
            • 두 가지의 조건
            • 여러 가지의 조건
          • switch~case 구문
          • while 구문
          • do~while 구문
          • for 구문
        • 랜덤(Random)
        • 배열
          • 1차원 배열
          • 2차원 배열
          • 다차원 배열
          • Sort
            • 선택 정렬
            • 버블 정렬
            • 삽입 정렬
      • Java 중급
        • 객체 지향 프로그래밍
        • 클래스
        • 인스턴스
        • 필드
        • 메소드
          • 설정(setter) 메소드
          • 반환(getter) 메소드
        • 생성자
        • 접근 제한
          • private
          • package
          • protected
          • public
        • 정적(static)
        • 불변(final)
        • 상수(constant)
        • 상속
          • this와 super의 이해
          • 멤버 변수 설정
          • 멤버 메소드 설정
          • 생성자 설정
        • 추상화
          • 추상 클래스
          • 인터페이스
        • 다형성
        • 중첩 클래스
          • 일반 중첩 클래스
          • static 중첩 클래스
          • 지역 중첩 클래스
          • 익명 중첩 클래스
      • Java API(작성중)
        • java.lang
        • java.util
        • java.text
        • java.time
        • java.io
        • java.net
        • java.sql
        • java.awt
        • javax.swing
      • Java 고급
        • 제네릭(Generic)
        • 열거형(Enum)
        • Annotation Type
          • Retention
          • Target
          • Nested Annotation
        • Java Reflection
          • Intro
          • Class
          • Field
          • Constructor
          • Method
          • Package
      • JDBC
        • 드라이버 로드
        • 연결 생성
          • JDBC Driver 유형
        • JdbcTemplate
      • Java 버전별 변경사항
        • Java 1.8
          • Lambda Expression
          • Stream API
          • java.time 패키지
        • Java 9
        • Java 12
          • switch~case
        • Java 13
          • Text Block
    • Arduino
      • 학습 준비
        • Reference
        • 아두이노 온라인 시뮬레이터
        • 전기의 이해
        • 그라운드(GND)의 이해
      • 개발 환경 구축
        • CH340 보드 설치
        • Editor 글꼴 설정
      • 아두이노 제어
        • 코드의 구성
        • 시리얼 출력
        • 디지털 출력
          • LED 출력
        • PWM 출력
        • 시리얼 입력
        • 디지털 입력
          • PIR 센서
        • 아날로그 입력
          • 온도 센서(LM35DZ)
          • 조도 센서
          • 가스 센서
        • 피에조 부저
        • 서보 모터 제어
          • 시리얼 서보 모터 제어
          • 스위치 서보 모터 제어
        • 온습도 센서(DHT-11)
        • LCD
      • 아두이노 통신
        • 블루투스(Bluetooth)
          • HC-06
            • 온도 센서 활용
          • HM-10
        • 와이파이(Wi-Fi)
          • ESP-01
            • WiFiEsp 라이브러리 추가
            • WiFiEsp 네트워크 스캔
        • 이더넷(Ethernet)
        • ArduinoJson 라이브리 사용
    • Regular Expression
  • Database
    • Oracle
      • 설치
        • SQL Plus
        • SQL Developer
        • DBeaver
        • Docker(Mac OS)
      • SQL
        • 관리자 명령
          • 사용자 관리
          • 권한 관리
          • Encoding 설정
          • 서비스 포트 설정
        • 사용자 명령
          • 테이블 관리
            • 테이블 항목 제약 조건
            • 외래키 제약조건
            • 데이터 유형
          • 시퀀스 관리
          • 데이터 관리
            • 데이터 추가
            • 데이터 조회
              • 오라클 내장 함수
              • 그룹 조회
              • Top N Query
            • 데이터 수정
            • 데이터 삭제
          • 뷰 관리
          • 인덱스 관리
          • 집합 연산
          • 테이블 조인
            • 등가 조인
            • 외부 조인
        • HR 계정
        • 기타 명령
          • 컬럼 간격 조정
      • 내보내기 및 불러오기
        • EXPDP, IMPDP
        • Docker로 실행중인 경우
      • 기타
        • 자동 세션 제거
        • Tablespace 관리
        • Unlock user
  • 면접대비
    • Q&A
      • Java
      • Database
      • Web
      • IT 일반상식
  • ETC
    • Eclipse IDE
      • 설치
      • 화면 설명
      • 환경 설정
      • 프로젝트 생성
      • 소스파일 작성 및 실행
    • Github
      • Github 계정 관리
      • Github 저장소 관리
        • Profile
        • Collaborators
        • Code
        • Issues
        • Pull requests
        • Action
          • Vue 3 Deploy Action
      • Personal Access Token
      • Git ignore 설정
        • Spring 개발용 샘플
      • Github Eclipse 연동
        • Branches
        • Project
        • Team project
          • Dynamic web project
          • Spring Boot Project
          • Branch 생성
          • Pull Request
          • Branch 보호
          • Branch 다시 생성
    • Figma
      • Team
      • Design
      • Component
    • 과정평가형
      • 실기 모의고사 1회
      • 실기 모의고사 2회
      • 실기 모의고사 3회
      • 실기 모의고사 4회
    • VScode
      • Live Server 실행 오류
      • Github 계정 변경
    • Naver ToastUI Editor
      • Editor 만들기
        • Editor options
          • File upload
      • Viewer 만들기
    • 문자 인코딩 방식
    • OBS
      • 녹화 잡음 제거 설정
    • Semantic Version
Powered by GitBook
On this page
  • Event 처리
  • Arrow function
  • 클래스 메소드 지정
  • Function.prototype.call() / .apply()
  • Function.prototype.bind()
  • Babel class-transform-properties
  • 결론
  1. Web
  2. Front-end
  3. JS
  4. ReactJS
  5. CDN(React18)
  6. Component
  7. 클래스 컴포넌트

event

class component에서의 Event 처리 방법에 대해서 살펴본다.

Event 처리

이벤트를 처리하기 위해서는 함수가 필요하며, 클래스 컴포넌트에 함수를 배치하는 방법은 여러 가지가 존재한다.

  • 화살표 함수(Arrow function)

  • 클래스 메소드 지정

  • Function.prototype.call() / .apply()

  • Function.prototype.bind()

  • Babel transform-class-properties 문법

Arrow function

화살표 함수로 이벤트를 처리할 경우 다음과 같이 작성한다. 다음 JSX 코드는 버튼을 클릭할 경우 알림창이 출력되는 코드이다.

<button onClick={()=>{window.alert('click event')}}>click</button>

추가 메소드를 구현하지 않아도 되므로 인라인으로 간편하게 처리할 수 있으나, 코드가 길어지면 가독성이 떨어지므로 간단한 코드 작성 시 유리하다. Arrow function 내에서 this라는 키워드를 사용할 경우 해당 컴포넌트 객체에 접근할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React CDN Example</title>
    
</head>
<body>

    <div id="app"></div>
    
    <!-- 개발용 CDN -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- 배포용 CDN -->
    <!-- <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script> -->
    <!-- <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> -->

    <!-- 바벨 CDN(using JSX) -->
    <script src=" https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        class MainComponent extends React.Component {
            render(){
                return (
                    <>
                        <button onClick={()=>{ alert('click event') }}>click</button>
                    </>
                );
            }
        }

        const app = ReactDOM.createRoot(document.querySelector("#app"));
        app.render(
            <MainComponent/>
        );
    </script>
</body>
</html>

클래스 메소드 지정

React Component Class 내부에 메소드를 만들고 이를 지정하여 호출할 수 있다.

class MainComponent extends React.Component {

    clickEventProcessor(){
        window.alert('click event');
    }

    render(){
        return (
            <>
                <button onClick={this.clickEventProcessor}>click</button>
            </>
        );
    }
}

클래스 메소드로 이벤트를 처리할 경우 문제점

위와 같이 클래스에 생성한 메소드로 이벤트를 처리할 경우 react component에 접근할 수 없다. this가 undefined로 출력되며, state, props 등 컴포넌트의 다른 구성요소에 접근할 수 없어 컴포넌트와 상관 없는 작업만 처리할 수 있다.

class MainComponent extends React.Component {
    clickEventProcessor(){
        console.log(this);
    }
    render(){
        return (
            <>
                <button onClick={this.clickEventProcessor}>click</button>
            </>
        );
    }
}

Function.prototype.call() / .apply()

Function에서 제공하는 call 함수와 apply 함수를 이용하면 this를 설정하며 함수 호출이 가능하다. 이를 이용하여 다음과 같이 이벤트를 설정할 수 있다.

class MainComponent extends React.Component {
    
    clickEventProcessor(){
        console.log(this);
        window.alert('click event');
    }
    
    render(){
        return (
            <>
                <button onClick={()=>this.clickEventProcessor.call(this)}>click</button>
                <button onClick={()=>this.clickEventProcessor.apply(this)}>click</button>
            </>
        );
    }
}

Function.prototype.call()과 Function.prototype.apply()는 동일한 기능을 수행하지만 다음 차이가 있다.

  • Function.prorotype.apply()는 인수를 배열로 전달한다.

  • Function.prototype.call()은 인수를 그대로 전달한다.

Function.prototype.bind()

Function.prototype.bind()를 사용하여 이벤트 처리 함수를 재할당 하여 사용하는 방법이 있다.

class MainComponent extends React.Component {

    constructor(){
        super();

        this.clickEventProcessor = this.clickEventProcessor.bind(this);
    }

    clickEventProcessor(){
        console.log(this);
        window.alert('click event');
    }

    render(){
        return (
            <>
                <button onClick={this.clickEventProcessor}>click</button>
            </>
        );
    }
}

핵심 코드는 생성자(constructor)에 있는 bind 코드이다.

this.clickEventProcessor = this.clickEventProcessor.bind(this);

clickEventProcessor에 this를 설정하여 재할당 한 뒤 사용하면 정상적으로 이벤트 함수에서 this가 MainComponent로 출력된다.

Babel class-transform-properties

Babel에서 제공하는 변환 코드를 사용하여 Function.prototype.bind() 대신 사용할 수 있다. 다음과 같은 형태로 이벤트 처리 메소드를 작성한다.

class MainComponent extends React.Component {

    constructor(){
        super();
    }

    clickEventProcessor = ()=>{
        console.log(this);
        window.alert('click event');
    }

    render(){
        return (
            <>
                <button onClick={this.clickEventProcessor}>click</button>
            </>
        );
    }
}

주의사항은 처리 함수는 반드시 화살표 함수로 작성해야 하며, 다음과 같이 작성하면 안된다는 것이다.

clickEventProcessor = function(){
    console.log(this);
    window.alert('click event');
}

실행하면 정상적으로 출력되는 것을 확인할 수 있다.

결론

이벤트 처리는 다음과 같은 방법으로 한다.

  • 간단한 이벤트 처리 - Arrow function

  • 복잡한 이벤트 처리 - Babel class-transform-properties

지원하는 이벤트의 종류는 다음과 같다.

  • Clipboard

  • Composition

  • Keyword

  • Focus

  • Form

  • Generic

  • Mouse

  • Pointer

  • Selection

  • Touch

  • UI

  • Wheel

  • Media

  • Image

  • Animation

  • Transition

  • ETC

PreviouspropsNextMouse

Last updated 2 years ago

합성 이벤트(SyntheticEvent) – React
Logo