icon안동민 개발노트

간단한 이벤트 처리하기


 React에서 이벤트 처리는 사용자 상호작용을 관리하는 핵심적인 부분입니다.

 React의 이벤트 시스템은 DOM 이벤트와 유사하지만, 몇 가지 중요한 차이점이 있습니다.

 이 절에서는 React에서 이벤트를 처리하는 방법과 주의해야 할 점들을 살펴보겠습니다.

React 이벤트 처리의 기본

 React에서 이벤트는 camelCase로 작성합니다.

 JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달합니다.

// HTML
<button onclick="handleClick()">Click me</button>
 
// React
<button onClick={handleClick}>Click me</button>

이벤트 핸들러 함수 작성하기

 이벤트 핸들러는 일반적으로 컴포넌트 내부에 메서드로 정의됩니다.

function Button() {
  const handleClick = () => {
    console.log('Button clicked!');
  };
 
  return <button onClick={handleClick}>Click me</button>;
}

다양한 이벤트 유형 처리하기

  1. 클릭 이벤트 (onClick)
function ClickExample() {
  const handleClick = () => {
    alert('Clicked!');
  };
 
  return <button onClick={handleClick}>Click me</button>;
}
  1. 폼 제출 이벤트 (onSubmit)
function FormExample() {
  const handleSubmit = (event) => {
    event.preventDefault(); // 기본 제출 동작 방지
    console.log('Form submitted');
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  );
}
  1. 입력 변경 이벤트 (onChange)
function InputExample() {
  const [value, setValue] = useState('');
 
  const handleChange = (event) => {
    setValue(event.target.value);
  };
 
  return <input value={value} onChange={handleChange} />;
}

이벤트 객체 사용하기

 React 이벤트 핸들러는 합성 이벤트(SyntheticEvent) 객체를 받습니다.

 이 객체는 브라우저의 네이티브 이벤트를 감싸고 있으며, 브라우저 간 일관된 속성을 제공합니다.

function InputWithLogging() {
  const handleChange = (event) => {
    console.log('Input value:', event.target.value);
    console.log('Input name:', event.target.name);
  };
 
  return <input name="example" onChange={handleChange} />;
}

이벤트 핸들러에 인자 전달하기

 때로는 이벤트 핸들러에 추가 매개변수를 전달해야 할 수 있습니다.

 이는 화살표 함수나 bind를 사용하여 할 수 있습니다.

function ItemList() {
  const handleItemClick = (id, event) => {
    console.log(`Item ${id} clicked`);
    console.log('Event:', event);
  };
 
  return (
    <ul>
      <li onClick={(event) => handleItemClick(1, event)}>Item 1</li>
      <li onClick={(event) => handleItemClick(2, event)}>Item 2</li>
    </ul>
  );
}

this 바인딩 문제와 해결 방법

 클래스 컴포넌트를 사용할 때 this 바인딩 문제가 발생할 수 있습니다.

 이를 해결하는 몇 가지 방법이 있습니다.

  1. 생성자에서 바인딩
class BindingExample extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
 
  handleClick() {
    console.log('This is:', this);
  }
 
  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}
  1. 클래스 필드 문법 사용
class BindingExample extends React.Component {
  handleClick = () => {
    console.log('This is:', this);
  }
 
  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}
  1. 화살표 함수 사용 (render 메서드 내부)
class BindingExample extends React.Component {
  handleClick() {
    console.log('This is:', this);
  }
 
  render() {
    return <button onClick={() => this.handleClick()}>Click me</button>;
  }
}

 함수형 컴포넌트에서는 이러한 this 바인딩 문제가 발생하지 않습니다.

이벤트 처리 시 주의사항

  1.  성능 고려 : 렌더링 메서드 내에서 화살표 함수를 사용하면 매 렌더링마다 새로운 함수가 생성될 수 있습니다. 성능에 민감한 경우 클래스 필드나 useCallback 훅을 사용하세요.

  2.  이벤트 위임 : React는 내부적으로 이벤트 위임을 사용하여 성능을 최적화합니다. 개발자가 직접 이벤트 위임을 구현할 필요는 없습니다.

  3.  비동기 이벤트 처리 : setTimeout이나 AJAX 콜백에서 이벤트 객체에 접근하려면 event.persist()를 호출해야 합니다.

function AsyncExample() {
  const handleClick = (event) => {
    event.persist();
    setTimeout(() => {
      console.log(event.type); // 'click'
    }, 1000);
  };
 
  return <button onClick={handleClick}>Click me</button>;
}

 React의 이벤트 시스템은 직관적이고 강력합니다.

 DOM 이벤트와 유사하지만 크로스 브라우저 호환성을 제공하고, 일관된 인터페이스를 제공합니다.

 이벤트 처리를 통해 사용자 상호작용에 반응하는 동적인 UI를 쉽게 만들 수 있습니다.

 주의해야 할 점들을 염두에 두고 적절히 이벤트를 처리하면, 더 반응적이고 사용자 친화적인 React 애플리케이션을 개발할 수 있습니다.