티스토리 뷰

Programming

[React] 이벤트 핸들링

whilescape 2019. 12. 6. 18:57

introduction

  1. event : user가 browser에서 dom 요소들과 상호 작용하는 것

4.1 리액트의 이벤트 시스템

  1. HTML 이벤트와 인터페이스가 동일하므로 꽤 비슷하다.
  2. 주의 사항
  • camelCase로 작성해야합니다.
  • 이벤트에서 실행할 js코드를 전달하는 것이 아니라, 함수 형태의 값을 전달
    화살표 함수 문법으로 함수를 만들어 전달한다.
  • dom 요소에만 이벤트를 설정할 수 있다.
    div, button, input, form, span 등 dom 요소에는 이벤트 설정 가능
    사용자가 직접 만든 컴포넌트에는 이벤트를 자체적으로 설정할 수 없다!
  1. 이벤트 종류
  • Clipboard
  • Composition
  • Keyboard
  • Focus
  • Form
  • Mouse
  • Selection
  • Touch
  • UI
  • Image
  • Wheel
  • Media
  • Animation
  • Transition

4.2 예제로 이벤트 핸들링 익히기

import React, { Component } from 'react';

class EventPractice extends Component {
    state={
        username: '',
        message: ''
    }


    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        });
    }

    handleClick = () => {
        alert(this.state.username + ': ' + this.state.message);
        this.setState({
            username: '',
            message: ''
        });
    }

    handleKeyPress = (e) =>{
        if(e.key === 'Enter'){
            this.handleClick();
        }
    }

    render() {
        return (
            <div>
                <h1>Event Practice</h1>   
                <input
                    type ="text"
                    name="username"
                    placeholder="username"
                    value={this.state.username}
                    onChange={this.handleChange}
                    onKeyPress={this.handleKeyPress}
                />  
                <input
                    type="text"
                    name="message"
                    placeholder="enter anything"
                    value={this.state.message}
                    onChange={this.handleChange}
                    onKeyPress={this.handleKeyPress}
                />
                <button onClick={this.handleClick}>
                    Check
                </button>
            </div>
        );
    }

}

export default EventPractice;
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함