🔑내 삶에는 어떤 이벤트가...
💡 이벤트 핸들러(Event Handler)란?
📃 이벤트 핸들러는 React에서 사용자와의 상호작용(예: 클릭, 입력, 마우스 이동 등)을 처리하는 함수입니다. React에서는 CamelCase 표기법을 사용합니다. onClick, onChange, onSubmit 등이 대표적입니다
💻클릭 이벤트 처리하기
import React from 'react';
function EventPractice() {
const handleClick = () => {
alert('버튼이 클릭되었습니다!');
};
return (
<button onClick={handleClick}>클릭하세요</button>
);
}
export default EventPractice;
⬆️ 버튼을 클릭하면 handleClick 함수가 실행되어 알림 창이 뜹니다
💡 이벤트 객체(event 객체) 활용
📃 React의 이벤트 핸들러에서 이벤트 객체는 event 매개변수를 통해 전달됩니다.
이 객체로 이벤트에 대한 정보를 얻을 수 있습니다.
💻이벤트 객체 사용하기
function EventPractice() {
const handleInput = (event) => {
console.log('입력된 값:', event.target.value);
};
return (
<input type="text" onChange={handleInput} placeholder="값을 입력하세요" />
);
}
export default EventPractice;
⬆️ 입력 필드에 값을 입력하면 event.target.value로 해당 값을 콘솔에 출력합니다
💡 클래스 컴포넌트에서 이벤트 핸들러 사용 constructor
📃 클래스 컴포넌트에서는 this를 사용하므로, 이벤트 핸들러를 클래스에 바인딩해야 합니다
💻클래스 컴포넌트 이벤트 핸들러 (constructor)
import React, { Component } from 'react';
class EventPractice extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert('클래스 컴포넌트에서 이벤트 실행');
}
render() {
return (
<button onClick={this.handleClick}>클릭</button>
);
}
}
export default EventPractice;
⬆️ handleClick 메서드를 this에 바인딩하여 이벤트 핸들러로 사용합니다
💡 클래스 컴포넌트에서 이벤트 핸들러 사용 bind ❌
📃 React에서는 ES6 이후 클래스 필드 문법을 지원하므로, 이벤트 핸들러를 화살표 함수로 선언하면 this 바인딩 문제를 자연스럽게 해결할 수 있습니다
💻클래스 컴포넌트 이벤트 핸들러 (화살표 함수)
import React, { Component } from 'react';
class EventPractice extends Component {
// state 초기화
state = {
message: "",
};
// 이벤트 핸들러 정의 (화살표 함수로 선언하여 this 바인딩 불필요)
handlerChange = (e) => {
console.log(e.target.value);
this.setState({ [e.target.name]: e.target.value });
};
handlerClick = () => {
this.setState({ message: "" });
};
render() {
return (
<div>
<input
type="text"
name="message"
placeholder="메세지를 입력해주세요"
value={this.state.message}
onChange={this.handlerChange}
/>
<button onClick={this.handlerClick}>삭제</button>
<h2>입력된 메세지: {this.state.message}</h2>
</div>
);
}
}
export default EventPractice;
⬆️ 화살표 함수는 this를 자동으로 현재 인스턴스에 바인딩하므로 추가적인 bind 작업이 필요 없습니다. 간결한 코드 작성이 가능하며, modern React 코드베이스에서 권장됩니다
💡 함수형 컴포넌트에서 이벤트 핸들러 사용
📃함수형 컴포넌트는 React Hook을 사용하여 상태 관리와 이벤트 처리를 간결하게 구현할 수 있습니다. 특히 useState를 활용하면 클래스 컴포넌트에서의 this.setState 대신 간단한 함수 호출로 상태를 업데이트할 수 있습니다
💻 함수형 컴포넌트에서 이벤트 핸들러 작성
import React, { useState } from 'react';
const EventPractice = () => {
// useState로 상태 초기화
const [message, setMessage] = useState("");
// 이벤트 핸들러 정의
const handleChange = (e) => {
console.log(e.target.value);
setMessage(e.target.value);
};
const handleClick = () => {
setMessage("");
};
return (
<div>
<input
type="text"
name="message"
placeholder="메세지를 입력해주세요"
value={message}
onChange={handleChange}
/>
<button onClick={handleClick}>삭제</button>
<h2>입력된 메세지: {message}</h2>
</div>
);
};
export default EventPractice;
⬆️ 함수형 컴포넌트는 상태 관리를 위해 useState를 사용하므로 클래스 컴포넌트의 this.state 및 this.setState에 비해 코드가 직관적입니다