Frontend/React
[React 기초 다지기] 4장 - 이벤트 핸들링
때오도르
2020. 1. 20. 23:43
※ 이 문서는 김민준 저자의 "리액트를 다루는 기술" 책을 통해 공부하며 정리한 내용 입니다.
사용자가 웹 브라우저에서 DOM 요소들과 상호작용 하는 것을 이벤트라고 합니다.
저서에서는 JSBin을 사용해서 테스트를 진행 하였다.
핵심내용
1. 리액트의 이벤트 시스템
1) 이벤트에 실행할 자바스크립트 코드를 전달하는 것이 아니라, 함수 형태의 값을 전달합니다.
2) DOM 요소에만 이벤트를 설정할 수 있습니다.
- div, button, form, span 등의 DOM 요소에는 이벤트를 설정할 수 있지만, 우리가 직접 만든 컴포넌트에는 이벤트를 자체적으로 설정할 수 없습니다.
- 리액트에서 지원하는 이벤트 종류
Clipboard, Touch, Composition, UI, Keyboard, Wheel, Focus, Media, Form, Image, Mouse, Animation, Selection, Transition
2. 이벤트 핸들링 하기
1) onChange 이벤트 핸들링하기
onChange={ (e) => { console.log(e); } }
- 콘솔로그에 기록되는 e 는 SyntheticEvent로 웹 브라우저의 네이티브 이벤트를 감싸는 객체 입니다. 이벤트가 끝나면 초기화 되므로 정보를 참조할 수는 없습니다. 만약 이벤트 객체를 참조할 일이 있다면 e.persist() 함수로 호출해 주어야 합니다.
- e.target.value 함수로 변경되는 값을 기록할 수 있습니다.
state = {
message: ''
}
...
render() {
return (
...
<input
...
value={this.state.message}
onChange={
(e) => {
this.setState({
message: e.target.value
})
}
}
/>
- 위와 같이 state 값에 input 값을 할당할 수 있습니다.
2) 임의 메서드 만들기
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value
});
}
handleClick() {
alert(this.state.message);
this.setState({
message: ''
});
}
...
<button onClick={this.handleClick}>확인</button>
- 이벤트에 실행할 자바스크립트 코드를 전달하는 것이 아니라, 함수 형태의 값을 전달합니다. 따라서 위와 같이 함수를 미리 준비하여 전달하는 방법도 있습니다. 성능상 거의 차이가 없으나 위 방법이 가독성이 높습니다.
3) Property Initializer Syntax를 사용한 메서드 작성
- 메서드 바인딩은 생성자에서 하는 것이 정석이지만, 새로운 메서드를 만들 때마다 constructor도 수정해야 하여 불편이 따릅니다. 이 작업을 간단히 하기 위해 바벨의 transform-class-properties 문법을 사용하여 화살표 함수 형태로 메서드를 정의할 수 있습니다.
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
handleClick = () => {
alert(this.state.message);
this.setState({
message: ''
});
}
- constructor를 제거하고 위 2개 함수만 남겨 훨씬 깔끔한 코드를 구현할 수 있습니다.
constructor(props) { super(props) this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); }
4) input 여러 개 다루기
- e.target.name을 사용하여 함수 하나로 여러개의 태그 이벤트를 다룰 수 있습니다.
state = {
username: '',
message: ''
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
...
<input
type="text"
name="username"
placeholder="사용자명"
value={this.state.username}
onChange={this.handleChange}
/>
...
객체 안에서 key를 [ ]로 감싸면 그 안에 넣은 레퍼런스가 가리키는 실제 값이 key 값으로 사용됩니다.
5) onKeyPress 이벤트 핸들링
handleKeyProess = (e) => {
if(e.key === 'Enter') {
thid.handleClick();
}
}
...
<input
...
onKeyPress={this.handleKeyPress}
/>