✅ 기본 개념: 이벤트 핸들러란?
이벤트 핸들러(handler)는 이름 그대로 이벤트를 다루는 함수다.
JSX에서는 onClick, onChange, onSubmit과 같은 on 접두어를 사용하는 속성에 이벤트 핸들러를 연결한다.
<button onClick={handleButtonClick}>
클릭1(이벤트핸들러 등록)
</button>
또는 아래처럼 함수를 직접 정의할 수도 있다.
<button onClick={() => console.log('Button Click')}>
클릭3(화살표 함수를 직접 정의)
</button>
✅ 자식 컴포넌트에게 이벤트 핸들러 전달하기
React에서는 컴포넌트 간 props를 통해 함수를 전달할 수 있다.
이때 이벤트 핸들러를 전달하면, 자식 컴포넌트에서 특정 이벤트 발생 시 부모의 함수를 호출하게 된다.
예를 들어, 아래와 같은 자식 컴포넌트 ButtonComponent는 onButtonClick이라는 prop으로 이벤트 핸들러를 받는다.
interface ButtonProps {
children: React.ReactNode;
onButtonClick: () => void;
}
function ButtonComponent({ children, onButtonClick }: ButtonProps) {
return (
<button onClick={onButtonClick}>
{children}
</button>
)
}
이 컴포넌트를 사용하는 부모 컴포넌트는 이렇게 핸들러를 넘겨줄 수 있다:
const buttonHandler = () => {
console.log('버튼 클릭');
}
<ButtonComponent onButtonClick={buttonHandler}>
이벤트 핸들러 (기능 전달)
</ButtonComponent>
✅ 사용자 입력 처리하기 - form 이벤트
form 태그의 onSubmit 이벤트는 기본적으로 페이지 새로고침을 유발한다.
React에서는 e.preventDefault()를 호출하여 이를 방지하고, 그 안에서 원하는 처리를 진행한다.
<form onSubmit={(e) => {
e.preventDefault();
console.log('전송 완료');
}}>
<input type="text" />
<button type="submit">전송</button>
</form>
✅ 상태(state)와 이벤트 연결하기
useState를 통해 상태를 관리하면, 이벤트를 통해 값 변경도 쉽게 연결할 수 있다.
아래처럼 setCount를 사용하는 증가/감소 버튼을 만들어보자:
const [count, setCount] = useState<number>(0);
<button onClick={() => setCount(count + 1)}>증가</button>
<button onClick={() => setCount(count - 1)}>감소</button>
<ChildComponent count={count} />
여기서 ChildComponent는 단순히 count 값을 받아 화면에 출력해주는 컴포넌트다.
✅ 이벤트 핸들러 작명 규칙 (권장)
- on+동작설명 : props로 전달할 때
- 예: onClick, onSubmit, onInputChange
- 동작+Handler : 함수 자체의 이름으로
- 예: clickHandler, submitFormHandler
'React' 카테고리의 다른 글
React - 이벤트 타입 처리 (0) | 2025.05.05 |
---|---|
React - UseState (0) | 2025.05.04 |
React - Rendering (1) | 2025.05.02 |
React - Props (0) | 2025.05.01 |
React와 JSX (2) | 2025.04.30 |