React - 이벤트 다루기

Noma·2021년 4월 13일
0

React 엘리먼트에서 이벤트를 처리하는 방식은 DOM 엘리먼트에서의 방식과 유사하지만, 아래와 같은 차이점이 있다.

  1. React의 이벤트는 소문자 대신 캐멀 케이스(camelCase) 를 사용
  2. JSX를 사용해 문자열이 아닌 함수 로 이벤트 핸들러를 전달

📍 예시

<button onClick={activateLasers}>
  Activate Lasers
</button>

🔍 HTML의 경우

<button onclick="activateLasers()">
  Activate Lasers
</button>
  1. React에서는 false를 반환해도 기본 동작을 방지할 수 없음
    → 반드시 preventDefault()를 호출해야 한다.
function ActionLink(){
	function handleClick(e){
      e.preventDefault();
      console.log('The link was clicked.');
    }
  	return (
      <a href="#" onClick={handleClick}>
        Click me
      </a>
    );
}

🔍 HTML의 경우

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>
  1. 컴포넌트 안에서 발생하는 이벤트를 처리해야 한다면 리액트의 synthetic event를 사용해야 한다.
    → onClick과 같은 곳에서 처리

  2. 컴포넌트와 관련 없는 이벤트(e.g. window scoll event)를 처리해야 할 때는 addEventListenercomponentDidMount()에 등록해야 한다.
    → 이후, 꼭 componentWillUnmount()에서 지워줘야 함


만약 컴포넌트가 Class인 경우, 아래와 같이 this binding을 해줘야 한다.

  • 생성자에서 bind()를 사용하는방법
class Toggle extend React.Component{
  constructor(props){
    super(props);
    this.state={isToggleOn:true};
    // this binding을 해줘야 한다.
    this.handleClick=this.handleClick.bind(this);
  }
  handleClick(){
    this.setState(state=>({
      isToggleOn:!state.isToggleOn
    }));
  }
  render(){
    return(
      <button onClick={this.handleClick}>
        {this.state.isToggleOn?'ON':'OFF'}
      </button>
    );
  }
}
  • 사용할 곳에서 bind()를 사용하는 방법
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        Click me
      </button>
    );
  }
}
  • Class Field를 사용해서 this 바인딩 (🌟추천)
constructor(){
...
}
handleClick = () => {
    console.log('this is:', this);
}
render(){
...
}

SyntheticEvent & nativeEvent

리액트에서 이벤트가 발생하면 이벤트 핸들러는 SyntheticEvent의 인스턴스를 전달한다. 즉 리액트로 개발 시 우리는 native event가 아니라 래핑된 이벤트(SyntehticEvent)를 사용하게 되는데, 이는 우리가 흔히 사용하는 stopPropagationpreventDefault를 포함하여 브라우저의 기본 이벤트(nativeEvent)와 동일한 인터페이스를 가지고 있다.

즉 우리가 리액트에서 사용하던 이벤트 핸들러는 S급 짝퉁이라는 것이다.
하지만 개발 도중 어떤 이유로 native event가 필요할 때를 대비해, 이벤트에 nativeEvent속성을 넣어놓았다.

이는 event.nativeEvent.stopImmediatePropagation()과 같이 접근 가능하다.

📚 reference

profile
Frontend Web/App Engineer

0개의 댓글