본문 바로가기

Javascript/React

React 바인딩(이벤트/메서드 연결)

반응형

자바스크립트에서 바인딩 (Javascript Binding)

결론부터 이야기하면 key point는 자바스크립트에서 "this"에 대한 이해가 완벽히 되어있어야 한다.

리액트 바인딩을 알아보기 전 자바스크립트에서 바인딩을 알아본다.

자바스크립트에서 객체안의 메서드에서 this는 그 메서드가 포함된 object를 가리키게 된다.  

1
2
3
4
5
6
7
8
var obj = {  
    prop: 'Hello',
    sayHello: function() {
        console.log( this.prop );
    }
};
 
obj.sayHello(); //"Hello"


즉, 위의 예제에서 sayHello 메서드안의 this는 obj객체가 되어 obj.prop인 Hello를 전달받아 콘솔 로그를 찍는다.

obj의 sayHello()를 다르게 출력해보면 undefined가 출력되는 것을 확인할 수 있다.

이 이유는 변수 reference에 담길 때 obj와의 관계가 상실되게 때문이다.

이럴 때 필요한 것이 "바.인.딩" 이다.

obj.sayHello()를 전달할 때 obj까지 바인딩시켜서 보내면 된다.

리액트에서도 마찬가지로 자바스크립트의 this가 사용되기때문에 바인딩이 필요하다.

리액트에서 바인딩 (React Binding)

React에서 컴포넌트에 이벤트메서드를 연결하는 방법 (=바인딩(binding))

다양한 방법이 있지만 리액트에서 주로 사용하는 방법은 컴포넌트의 생성자에서 바인딩 하기다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class App extends React.Component {
    constructor() {
        super();
        this.state = {
              hidden: false,
        };
        this.update = this.update.bind(this);
    }
    update() {
        this.setState({
            hidden: true
        });
    }
 
    render() {
        return <div
            onClick={ this.update }
        />;
    }
 
}


constructor() 에서 this.update = this.update.bind(this); 문장을 집어넣어서 바인딩시키면 render()에서 onClick={this.update}를 할 때 this가 App컴포넌트의 this라는 것을 알게 되는 것이다.


바인딩하는 방법중에 'autobind-decorator'를 사용해서 바인딩할 수 도 있다.

1
2
3
4
5
6
7
8
9
import autobind from 'autobind-decorator'
 
class App extends React.Component {  
    @autobind
    update() {
        ...
    }
    //...생략...
}


이 방법을 소개한 이유는 ES2015에서 제공하는 기능인 arrow function을 사용하면 this를 자동으로 바인딩 해준다고 한다. (babel-preset-stage-2 패키지 필요)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { Component, PropTypes } from 'react';
 
export default class Basic extends Component {
    state = {
           hidden: false,
      };
 
      onClickButton = () => {
        this.setState(() => ({ hidden: true }));
      }
    
    render() {
        return (
              <div>
                <button onClick={this.onClickButton}>숨기기</button>
              </div>
        );
    }
}


onClickButton 메서드를 "() =>" arrow function으로 만들었다. (auto binding)

ES2015문법을 사용하는게 장기적으로 이득이니 적응하는게 좋을 듯 하다.


참고사이트

https://www.zerocho.com/category/React/post/578232e7a479306028f43393

https://medium.com/@khwsc1/react%EC%97%90%EC%84%9C%EC%9D%98-%EB%B0%94%EC%9D%B8%EB%94%A9-binding-%EB%B0%A9%EB%B2%95%EB%93%A4-a595ff9190b6

반응형

'Javascript > React' 카테고리의 다른 글

Props, State (리액트 컴포넌트 속성, 상태)  (0) 2017.10.13
JSX (React Component)  (2) 2017.10.11
리액트(React) 환경 설정 (create-react-app)  (2) 2017.10.09
리액트(React)  (0) 2017.10.08