포스코x코딩온 웹 풀스택 양성과정

[포스코x코딩온] 웹 풀스택 과정 12주차 회고 | React - 이벤트 핸들링

Codult 2024. 4. 5. 15:05
728x90

📌 React의 이벤트

💡 주의점

  • 카멜케이스(camelCase) 이용한다.
  • JSX로 이벤트 핸들러 전달한다.
{/* 잘못된 예시 */}
<button onclick={activeEvent()}>버튼</button>
{/* 올바른 예시 */}
<button onClick={activeEvent}>버튼</button>
  • 기본 DOM 요소에만 이벤트 설정 가능하다.
    (직접 만든 컴포넌트에 이벤트 자체 설정이 불가능하다. 해당 컴포넌트로 props를 전달하는 의미가 됨)
{/* 아래의 경우, 이름이 onClick인 props를
MyButtonComponent 컴포넌트에 전달해주는 것을 뜻함*/}
<MyButtonComponent onClick={activeEvent}/>


💡 함수에 인자 보내기

  • 화살표 함수를 이용하여, 인자를 보낸다.
<button onClick={() => onClickEvent("인자")}>이벤트1</button>
<button onClick={(e) => onClickEvent(e, "인자")}>이벤트2</button>

💡 클래스 컴포넌트에서의 이벤트

  • 클래스형 컴포넌트의 경우, this.을 사용해야 함수를 찾아갈 수 있다. (props와 마찬가지로)
<button onClick={this.activeEvent}>버튼</button>
  • 클래스형 컴포넌트의 경우, this를 바인딩하는 과정을 거쳐야, this를 찾아갈 수 있다. (화살표 함수를 이용하는 경우에는, 이 과정을 생략할 수 있다.)
constructor(props) {
  super(props);
  this.eventExample = this.eventExample.bind(this);
}
eventExample() {
  console.log(this)
}
// 화살표 함수의 경우, 바인딩없이 바로 this 사용 가능
eventExample2 = () => {
  console.log(this)
}
 
728x90