Event-System

  1. 직접 이벤트 속성에 이벤트 핸들러 함수 정의하며 이벤트 연결
class EventButton extends React.Component {

/* constructor를 생략하면 아래 구문을 적어준다. */
constructor(props) {
    super(props);
}
render() {
    console.log(this.props);

    return (
        <button onClick={() => alert('인라인 함수 이벤트 동작 확인')}>{this.props.children}</button>
    );
}
ReactDOM.createRoot(document.getElementById('root')).render(
 <EventButton>이벤트버튼</EventButton>
);

→ Class형 컴포넌트라 기본 생성자를 만들어야 한다.

  1. render 함수 외부에 이벤트 핸들러 함수 정의 후 함수 전달하여 이벤트 연결
onClickHandler = () => alert('외부 함수 이벤트 동작 확인');

render() {
    return (
        <button onClick={this.onClickHandler}>{this.props.children}</button>
    );
}
  1. component에 이벤트를 props로 전달 후 연결
render() {
    console.log(this.props);
    const { onClick, children } = this.props;
    return <button onClick={onClick}>{children}</button>;
}

/* 컴포넌트 실행 부분*/
<EventButton onClick={() => alert('props로 이벤트 전달 후 연결 확인')}>
    이벤트 버튼
</EventButton>

[주의 사항]

  1. 이벤트 속성의 이름은 캐멀 표기법으로 작성해야 한다.
  2. 이벤트 실행 할 자바스크립트의 코드를 전달하는 것이 아닌 함수 형태의 값을 전달
  3. DOM 요소에만 이벤트를 설정할 수 있다.