Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 냥이
- codejam
- 발산역 근처 카페
- 부모님과
- 커플
- 레스토랑
- 소호정본점
- 고양이
- 데이트
- CodeJam 2017 Round 1B
- 안동국시
- 냥스토리
- 카페
- 냥냥
- 발산
- 먹기좋은곳
- 소호정
- 고양이는 언제나 귀엽다
- 치명적 귀여움
- 스테이크
- 파머스테이블
- coffee
- 양재맛집
- 스파게티
- CDJ
- 스코티쉬 스트레이트
- 발산맛집
- 파버스
- RED CAT COFFEE X LOUNGE
- A. Steed 2: Cruise Control
Archives
- Today
- Total
hubring
이벤트 핸들링 본문
이벤트 핸들링 주의 사항
1. 이벤트 이름은 카멜 표기법 작성
2. 이벤트에 실행할 자바스크립트 코드를 전달하는 것이 아닌 함수 형태의 값을 전달함.
3. DOM 요소에만 이벤트를 설정 가능
=> 만약 직접 만든 컴포넌트에 설정할 경우 이벤트가 아닌 props로 값 전달됨.
이벤트 종류
Clipboard, Touch, Composition, UI, Keyboard, Wheel, Focus,
Media, Form, Image, Mouse, Animation, Selection, Transition
이벤트 핸들링 매뉴얼
https://reactjs.org/docs/handling-events.html
Handling Events – React
A JavaScript library for building user interfaces
reactjs.org
클래스형 컴포넌트 예제
// 클래스형 컴포넌트로 구현한 EventPractice
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>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="유저명"
value={this.state.username}
onChange={this.handleChange}
/>
<input
type="text"
name="message"
placeholder="아무거나 입력해보세요"
value={this.state.message}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
/>
<button onClick={this.handleClick}>확인</button>
</div>
);
}
}
export default EventPractice;
함수형 컴포넌트 예제
import React, { useState } from 'react';
const EventPractice = () => {
const [form, setForm] = useState({
username: '',
message: ''
});
const { username, message } = form;
const onChange = e => {
setTimeout(() => console.log(e), 500);
const nextForm = {
...form, // 기존의 form 내용을 이 자리에 복사 한 뒤
[e.target.name]: e.target.value // 원하는 값을 덮어씌우기
};
setForm(nextForm);
};
const onClick = () => {
alert(username + ': ' + message);
setForm({
username: '',
message: ''
});
};
const onKeyPress = e => {
if (e.key === 'Enter') {
onClick();
}
};
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="유저명"
value={username}
onChange={onChange}
/>
<input
type="text"
name="message"
placeholder="아무거나 입력해보세요"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
/>
<button onClick={onClick}>확인</button>
</div>
);
};
export default EventPractice;
참고.
리액트를 다루는 기술 - 김민준 지음, 길벗 출판
'Javascript > React' 카테고리의 다른 글
React - Router 사용방법 (0) | 2020.07.01 |
---|---|
Ref 사용하기 (0) | 2020.06.23 |
React - Class VS Functional Component (0) | 2020.06.22 |
React 개발하기 (0) | 2020.06.16 |
React 환경설정 (0) | 2020.06.15 |