👉 React 요소에서 이벤트를 핸들링 하는 방식은 DOM 요소의 이벤트를 핸들링 방식과 유사하다.
문법적인 차이는 다음과 같다.
✍Exmple
const PreventBrowserDefaultAction = () => {
handleClick(e) {
e.preventDefault();
console.log('브라우저 기본 동작을 차단');
}
return (
<a
href="https://google.com/"
onClick={ handleClick }
>
Google
</a>
)
}
👉 클래스 컴포넌트를 사용할 경우, 메서드이 this는 참조(ref)에 대해 주의가 필요하다.
또한 이벤트 핸들러 내에서 this
를 호출 할 경우 undefined
값을 반환하게 된다.
👉 this
대신에 e.target
, e.currentTarget
으로 사용해야 된다.
✍ Exmple
class PreventBrowserDefaultAction extends Component {
handleClick(e) {
e.preventDefault();
console.log(this);
console.log(e.target, e.currentTarget);
}
render() {
return (
<a
href="https://google.com/"
onClick={this.handleClick}
>
Google
</a>
)
}
}
React의 해결책은 브라우저 내장 이벤트를 감싸는 것이다. 웹 페이지를 실행하는 브라우저의 구현에 관계없이, 이벤트가 W3C 명세를 따르도록 만들었다. 내부적으로 React는 합성 이벤트를 위한 특별한 클래스를 사용한다. SyntheticEvent 클래스의 인스턴스를 이벤트 핸들러에 전달 하는 것이다.
👉 클래스 컴포넌트의 JSX 이벤트 핸들링에서 이벤트 속성에 연결된 메서드의 this
참조가 undefiend
일 경우 제대로 작동하지 않는 문제가 발생한다. 이를 해결 위한 여러 가지 방법을 정리.
👉 JavaScript 함수는 bind()
메서드를 사용해 this
참조를 임의로 변경할 수 있다. 이 방법을 사용하여 메서드의 this
참조가 컴포넌트 인스턴스 가리키도록 변경해야한다.
✍ Exmple
class PreventBrowserDefaultAction extends Component {
constuctor() {
super()
// this 참조를 컴포넌트 인스턴스로 변경
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
e.preventDefault()
console.log(this) // this === PreventBrowserDefaultAction {}
}
render() {
return (
<a href="https://google.com/" onClick={this.handleClick}>Google</a>
)
}
}
생성자(constructor) 라이프 훅에서 bind()를 통해 this 참조를 변경하지 않고 아래와 같이 메서드에 직접
bind()
를 사용해 this 참조를 변경할 수 있다.✍ Exmple
class PreventBrowserDefaultAction extends Component { handleClick(e) { // ... } render() { return ( <a href="https://google.com/" onClick={this.handleClick.bind(this)} Google </a> ) } }
👉 컴포넌트 메서드를 래핑하는 익명 함수(화살표 함수)를 사용하면 이벤트 발생 시 this
참조 컴포넌트 인스턴스를 설정할 수 있다.
✍ Exmple
class PreventBrowserDefaultAction extends Component {
handleClick(e) {
// ...
}
render() {
return (
<a
href="https://google.com/"
onClick={ (e) => this.handleClick(e) }
>
Google
</a>
)
}
}
👉 ES5 표준에 제안된 문법인 클래스 필드 구문을 사용해 문제를 해결할 수 도 있다. 객체의 향상된 표기법 대신 화살표 함수 방식으로 메서드를 정의하면 this 참조가 컴포넌트 인스턴스 가리키게 된다.
✍ Exmple
class PreventBrowserDefaultAction extends Component {
// handleClick() {
handleClick = (e) => {
e.preventDefault();
console.log(this); // this === PreventBrowserDefaultAction {}
}
render() {
return (
<a href="https://google.com/" onClick={this.handleClick}>Google</a>
)
}
}
👉 React 컴포넌트 메서드(이벤트 리스너 일 경우)에 특정 인자를 전달하는 방법은 두 가지가 있다.
👉 클래스 컴포넌트의 메서드를 래핑하는 화살표 함수를 이벤트 속성에 연결한 후, 특정 인자를 전달할 수 있다.
✍ Exmple
<BaseButton
onClick={ (e) => this.handleClick(id, e) }
>
...
</BaseButton>
👉 클래스 컴포넌트 메서드에 특정 인자를 전달해 실행한 후, JavaScript 함수의 bind*()
메서드를 사용해 this
참조 변경한다.
✍ Exmple
<BaseButton
onClick={ this.handleClick.bind(this, id) }
>
...
</BaseButton>