저희는 이전에 이벤트를 실행할 자바스크립트 코드를 전달하는 것이 아닌, 함수 형태의 값을 전달합니다. 라고 배웠습니다.
그렇기에 지금까지의 함수를 직접 만들어서 실행하였지만
함수를 미리 준비하여 전달하는 방법도 있습니다.
// EventPractice.js
import React, { Component } from "react";
class EventPractice extends Component {
state = {
message: "",
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value
});
console.log(e.target.value);
}
handleClick() {
alert(this.state.message);
this.setState({
message: ''
});
}
render() {
return (
<div>
<h1>이벤트 연습!</h1>
<input
type="text"
name="message"
placeholder="메세지를 입력해보세요"
value={this.state.message}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>확인</button>
</div>
);
}
}
export default EventPractice;
이렇게 미리 함수를 만들어서 사용하는 방법은
성능상으로는 차이가 거의 없지만 가독성은 훨씬 뛰어납니다.
(물론 경우에 따라 내부에서 함수를 만드는 것이 더 편한 경우도 있습니다.)
우리는 “일반적인 함수에서 this는 함수 자신을 가르킨다.” 라고 배웟습니다.
그것과 같은 의미로
handleChange함수에서 this는 handleChange함수 자기 자신을 가르킵니다.
따라서
constructor
에서 handleChange함수의 ‘this’는 constructor
를 가르킨다. 라고 선언해주는 것입니다.
다시말해 생성자(EventPractice)를 가르킬 수 있도록 bind해주는 역할을 합니다.
이 코드를 풀어서 설명하자면,
this.handleChange = this.handleChange.bind(this);
handleChange 메서드 내부의 this를 EventPractice클래스의 인스턴스에 연결(bind)하여, 메서드가 실행될 때마다 this가 해당 인스턴스를 참조하도록 한다.
EventPractice가 왜 나오는지 이해하기 어려울 수 있는데,
constructor메서드는 EventPractice클래스의 인스턴스가 생성될 때 호출되는 메서드 입니다.
따라서 constructor
의 ‘this’는 EventPractice
를 가리킵니다.
매우 간단하게 화살표 함수를 사용하여 해결할 수 있습니다.
// constructor 메서드를 삭제합니다.
...
handleChange = (e) => {
this.setState({
message: e.target.value
});
console.log(e.target.value);
}
handleClick = () => {
alert(this.state.message);
this.setState({
message: ''
});
}
...
우리는 화살표 함수를 사용할 경우
화살표 함수의 ‘this’는 해당 함수가 종속된 인스턴스를 지칭한다고 이미 배웠습니다.
따라서 handleChange함수와 handleClick함수를 화살표 함수로 만들면
두 함수의 ‘this’는 EventPractice
를 가르키므로 문제없이 사용할 수 있게 됩니다.
※ 주의해야 할점
화살표 함수를 사용하여 this를 가르키는것은 맞지만
class의 클래스 필드(이 경우엔 state와 그안의 message)를 사용하기위해
바벨의 transform-class-properties
플러그인을 사용합니다.
즉,
EventPractice
를 가리키는것은 맞습니다.가독성의 차이를 느낄 수 있나요?