이벤트 핸들러 바인딩

WOOSUNG·2022년 12월 14일
0

REACT

목록 보기
11/11

React에서 이벤트 핸들러를 바인딩 하는 방법에 대해 설명합니다.

JS 문법과 아래 사항에 대해 공부를 하셔야 합니다.

  • Component
  • Arrow Function(화살표 함수)
  • state

※ Hook을 사용하지 않더라도 arrow function는 효율적인 기능을 제공하며 코드를 간결하게 해주므로 공부하시면 많은 도움이 됩니다.


이벤트 핸들러 바인딩이란?

컴포넌트와 이벤트 함수를 연결(bind)하는 것입니다.

바인딩하지 않아도 이벤트 함수는 실행이 되지만 누가 호출을 했는지 알 수가 없습니다.

누가 호출 했는지 알 수 없으므로 this.props 또는 this.state에 접근할 경우 undefined로 처리 됩니다.


이벤트 핸들러를 바인딩하지 않고 this를 사용하는 경우

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };
  }

  NotBindingBtnClick() {
    console.log(this.state.applyText);
  }

  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={this.NotBindingBtnClick}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}

**내가 생각하는 로직**

  1. TestComponent의 생성자(constructor)가 실행 되면서 state.applyText의 값이 "빈 값"으로 초기화
  2. TestComponent Render 완료
  3. TestComponent에서 버튼을 클릭
  4. NotBindingBtnClick 이벤트 함수 실행
  5. console.log에서 this.state.applyText값 확인

내가 생각하는 결과

"빈 값"

실제 결과

undefined


undefined가 나온 이유?

JS에서 undefined는 변수 또는 객체 또는 객체의 속성이 존재하지 않을 경우입니다.

null과 비교해서 설명을 하자면, null은 변수는 존재하지만 값이 없는 경우이고 undefined는 변수도 존재하지 않는 경우입니다.

이벤트 함수에서 사용한 this는 TestComponent를 의미합니다.

JSX는 this(=TestComponent)을 bind 하지 않으므로 이벤트 핸들러 함수에서 this를 사용할 경우 생성자에서 이벤트 핸들러 함수를 bind하거나 arrow function을 사용해야합니다.

arrow function는 정적으로 bind되는게 아니라 함수가 어떻게 호출되었는지에 따라서 바인딩할 객체가 동적으로 결정됩니다.


이벤트 핸들러를 바인딩 하는 방법

1) 생성자(constructor)에서 바인딩

Component에 바인딩 해야하는 이벤트가 많아질수록 코드가 길어진다는 단점이 있습니다.

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };

    this.NotBindingBtnClick = this.NotBindingBtnClick.bind(this);
  }

  NotBindingBtnClick() {
    console.log(this.state.applyText);
  }

  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={this.NotBindingBtnClick}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}

2) 화살표 함수 사용 방법 1.

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };
  }

  NotBindingBtnClick = () => {
    console.log(this.state.applyText);
  }

  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={this.NotBindingBtnClick}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}```


**3) 화살표 함수 사용 방법 2.**

```js
class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };
  }

  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={this.NotBindingBtnClick = () => {console.log(this.state.applyText);}}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}

4) 화살표 함수 사용 방법 3.

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };
  }

  NotBindingBtnClick = () => {
    console.log(this.state.applyText);
  }
  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={() => this.NotBindingBtnClick()}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}

5) 이벤트 선언과 바인딩

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { applyText: "빈 값" };
  }

  NotBindingBtnClick = () => {
    console.log(this.state.applyText);
  }

  render() {
    return (
      <React.Fragment>
        <button type="button" onClick={this.NotBindingBtnClick.bind(this)}>
          NotBinding
        </button>
      </React.Fragment>
    );
  }
}

6) Hook을 이용한 Arrow Function Component

Hook을 이용하여 함수형 컴포넌트를 구현할 경우 생성자(constructor)가 필요 없으며, this를 사용하지 않아도 됩니다.

const TestComponent () => {
   const [applyText, setApplyText] = useState('빈 값');

  return (
    <React.Fragment>
      <button type="button" onClick={() => console.log({applyText})}>
        NotBinding
      </button>
      <ListComponent applyText={applyText} />
    </React.Fragment>
  );
}

0개의 댓글