개발새발개발/React

[React] 이벤트 핸들링, 합성 이벤트 객체

birdsfoot 2025. 2. 3.

 

 

 

이벤트 핸들링

 

- 이벤트가 발생했을 때 그것을 처리하는 것

ex) 버튼 클릭 시 경고창 노출 등

 

 

버튼 클릭 이벤트 만들기 

방법 1

const Button = ({text,color,children}) => {

    return (
    <button 
    onClick={() => {
        console.log(text)
    }}
    style={{color :color}}>{text}
    </button>
    )
}


Button.defaultProps = {
    color : "blue"
}

export default Button

 

 

방법2

const Button = ({text,color,children}) => {


    const onClickButton = () => {
        console.log(text)
    }
    return (
    <button 
    onClick={onClickButton}
    style={{color :color}}>{text}
    </button>
    )
}


Button.defaultProps = {
    color : "blue"
}

export default Button

 

 

- 콜백함수처럼 따로 선언해줄 수 있음

- 주의할 점은 ( ) 없이 함수의 이름만 넣으면 된다는 것! 

 

 

 

버튼 위에 마우스 올렸을 때 이벤트 핸들링

const Button = ({text,color,children}) => {


    const onClickButton = () => {
        console.log(text)
    }
    return (
    <button 
    onClick={onClickButton}
    onMouseEnter={onClickButton}
    style={{color :color}}>{text}
    </button>
    )
}


Button.defaultProps = {
    color : "blue"
}

export default Button

 

onMouseEnter={onClickButton}

 

- onMouseEnter 코드는 버튼 위에 마우스를 올렸을 때 실행됨

 

 

 

합성 이벤트 객체

 

 

- 전달받은 이벤트 객체를 살펴보면 합성 이벤트 객체(SyntheticBaseEvent)라고 뜸

 

- 합성 이벤트 객체 :  모든 웹 브라우저의 이벤트 객체를 하나로 통일한 형태 

- 즉, 모든 브라우저에서 사용 가능한 통일된 이벤트 객체

- 발생한 이벤트와 관련된 모든 정보가 담겨 있음 

 

 

 

- 브라우저가 너무 다양하기 때문에 이벤트 객체도 브라우저마다 조금씩 다름

 

- 여러 브라우저의 규격을 참고해 하나의 통일 된 규격으로 이벤트 객체를 포맷팅해줌

 

 

 

 

출처 : 인프런 ) 한 입 크기로 잘라 먹는 리액트 - 이정환 

댓글