티스토리 뷰

사용자 이벤트를 만들기 전에

.bind(this){}라는 녀석을 살펴보자.

.bind(this)란, 간단하게 말해서 컴포넌트 그 자체를 가르킨다

ex) <App> Component

따라서 bind(this)를 해주는 경우에는 <App>컴포넌트 자체를 심어준다는 의미이다. 그렇다면 그 <App>에서 사용하는

state 값들을 사용할 수 있다.

 

 

사용자 이벤트 만들기

먼저,

App.js

<div className="App">
             <Subject title ={this.state.subject.title}
             sub ={this.state.subject.sub}
             onChangePage = {function(){
                alert("thithithi");
                //bind(this)의 this 로 state 값을 변경 가능하다
              	//state 값을 변경할 때는 setState를 꼭 사용하자
               this.setState({
					mode : 'read' // mode라고 선언했던 임의의 state 값 read로 변경
				)};
             }.bind(this)}
             >
            </Subject>

위와 같은 코드가 있다고 했을 경우에 

해당 div 영역에서 onChangePage 라는 사용자 정의 이벤트를 설치했다고 생각하자. 

 

Subject.js

import React,{ Component} from 'react';
class Subject extends Component{
    render() {
        return (
            <header>
                <h1>
                    <a href="/" onClick = { function(e){
                            e.preeventDefault();
                            this.props.onChangePage();  // bind(this)로 받은 this를 활용하여 부모 이벤트 호출
                    }.bind(this)}>{this.props.title}</a>
                </h1>
                    {this.props.sub}
            </header>
        );
    }
}

export default Subject;

Subject.js에서는 bind.(this)를 활용하여 부모의 this 값을 가져와 심어준다.

그 후, 부모에서 만들어준 사용자 이벤트를 호출하면 된다.