여러분이 사용하고 계신 브라우저는 HTML5를 지원하지 않기 때문에 몇몇 요소가 제대로 보이도록 JScript를 사용하고 있습니다. 하지만 여러분의 브라우저 설정에서 스크립트 기능이 꺼져있으므로, 현재 페이지를 제대로 확인하시려면 스크립트 기능을 켜주셔야 합니다. React - 이벤트
React – 이벤트
3개월전 작성
4개월전 수정

React

이벤트

HTML DOM 이벤트와 마찬가지로 React는 사용자 이벤트를 기반으로 작업을 수행할 수 있다.

React에는 HTML과 동일한 이벤트(클릭, 변경, 마우스 오버 등)가 있다.

이벤트 추가

React 이벤트는 camelCase 구문으로 작성된다.

onclick 대신 onClick.

React 이벤트 핸들러는 중괄호 안에 작성된다.

onClick=”shoot()” 대신 onClick={shoot}.

예제 – React
<button onClick={shoot}>Take the Shot!</button>
예제 – HTML
<button onclick="shoot()">Take the Shot!</button>
예제

Football 구성 요소 안에 Shoot 함수를 넣는다.

function Football() {
  const shoot = () => {
    alert("Great Shot!");
  }

  return (
    <button onClick={shoot}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
기본 예시
예제 보기

인수 전달

이벤트 핸들러에 인수를 전달하려면 화살표 함수를 사용하자.

예제

화살표 함수를 사용하여 “Goal!”을 촬영 함수에 파라미터로 보낸다.

function Football() {
  const shoot = (a) => {
    alert(a);
  }

  return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
기본 예시
예제 보기

React 이벤트 객체

이벤트 핸들러는 함수를 트리거한 React 이벤트에 액세스할 수 있다.

예제

화살표 기능: 이벤트 객체를 수동으로 보내기

function Football() {
  const shoot = (a, b) => {
    alert(b.type);
    /*
    'b' represents the React event that triggered the function,
    in this case the 'click' event
    */
  }

  return (
    <button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
기본 예시
예제 보기
참고
Mingg`s Diary
밍구
공부 목적 블로그