[React] event 처리 시 bind와 Arrow Function

Nowod_K·2022년 6월 2일
0

React에서 함수를 호출 할 때 뒤에 () 를 붙이지 않고 호출하는 경우 함수를 bind 처리해야한다
javascript에서는 class method에 this가 기본적으로 바인딩 되어있지 않기 때문이다.

이를 해결하기 위한 3가지 방법이 있다.

1. bind 함수 사용.

constructor에 직접 바인딩을 해준다.

class TodoInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '',
        }
      
      	// 콜백에서 'this'가 사용되려면 바인딩해주어야 한다.
      	this.handleClick = this.handleClick.bind(this)
    };

    handleClick(e) {
        console.log('handleClick');
    };

    render() {
        return (
            <>
                <div className="TodoInput">
                    <input placeholder="새로운 Todo를 입력해주세요"/>
                    <button onClick={this.handleClick}>등록</button>
                </div>
            </>
        )
    }
}

2. 함수 호출 시 Arrow Function 사용

class TodoInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '',
        }
    };

    handleClick(e) {
        console.log('handleClick');
    };

    render() {
        return (
            <>
                <div className="TodoInput">
                    <input placeholder="새로운 Todo를 입력해주세요"/>
          // onClick 부분에 Arrow Function을 사용하여 해결한다.
                    <button onClick={(e) => {this.handleClick(e)}}>등록</button>
                </div>
            </>
        )
    }
}

3. 함수 구현 시 Arrow Function 사용

class TodoInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '',
        }
    };
	
   	// 함수 구현부에 Arrow Function을 사용하는 경우
    handleClick = (e) => {
        console.log('handleClick');
    };

    render() {
        return (
            <>
                <div className="TodoInput">
                    <input placeholder="새로운 Todo를 입력해주세요"/>
                    <button onClick={this.handleClick}>등록</button>
                </div>
            </>
        )
    }
}

Arrow Function을 쓸 때 바인딩을 할 필요 없는 이유는 Arrow Function의 특징 때문이다. Arrow Function은 상위의 scope의 this를 상속받기 때문에, 굳이 바인딩 과정이 필요없다. (ES6 만세)

나는 개인적으로 3번째 방법 '함수 구현 시 Arrow Function 사용'이 마음에 든다.

함수를 구현할때만 좀 신경 쓰면 호출하거나 사용하거나 할 때 큰 고민을 안해도 되니, 훨씬 사용성이 좋지 않나 생각이든다.

profile
개발을 좋아하는 마음과 다양한 경험을 토대로 좋은 개발자가 되고자 노력합니다.

0개의 댓글