Component Event

Front-end Dev. Hyuk·2020년 8월 23일
0

React

목록 보기
15/15

나는 event의 소비자였지 생성자는 아니여서 잘 모르겠지만 한번 습득해보자!
이전에 작업했던 subject component을 다시 살렸다.

render() {
  console.log('App render')
  var _title, _desc = null;
  if(this.state.mode === 'welcome'){
    _title = this.state.welcome.title;
    _desc = this.state.welcome.desc;
  } else if (this.state.mode === 'read'){
    _title = this.state.Contents[0].title;
    _desc = this.state.Contents[0].desc;
  }
    return (
      <div className="APP">
        <Subject title = {this.state.Subject.title} 
        sub={this.state.Subject.sub}></Subject>
        <TOC data = {this.state.Contents}></TOC>
        <Content title = {_title} desc ={_desc}></Content>
      </div>
    );
  }
} 

export default App;

만약에 subject라는 component를 사용할때 사용자가 링크를 클릭했을때

class Subject extends Component {
    render() { 
      return (
        <header>
          <h1><a href="/">{this.props.title}</a></h1>
          {this.props.sub}
          </header> 
      );
    }
  }

어떠한 일이 일어나게 하고싶다면 onChangepage라고 하는 이벤트를 써야하고 그 이벤트의 함수를 설치해 놓으면 위에보는 a href tag가 클릭되었을 때 내가 작성한 함수를 실행해준다고 작성할 것이다.

그래서 onChangepage에 작성을하면되는데 다음과 같이 작성한다.
그래서 page가 바뀌었을때 component를 설치한 이 함수를 호출해주기만 하면되고 어떤 형태로 전달해줄까 생각해보면 props전달해 주면된다고 생각하면된다.

 <Subject title = {this.state.Subject.title} 
        sub={this.state.Subject.sub}
          onChangepage={function(){
            alert('hihihi');
          }.bind(this)}
          >
        </Subject>

그리고 그것을 Subject.js 파일에서 설정을 해준다.


class Subject extends Component {
    render() { 
      return (
        <header>
          <h1><a href="/" onClick={function(e){
            e.preventDefault();
            this.props.onChangePage();
          }.bind(this)}>{this.props.title}</a></h1>
          {this.props.sub}
          </header> 
      );
    }
  }

export default Subject;

a tag에 클릭했을때 다음과 같이 작동되도록 하였다. 실행했을때 preventDefault를 작성해서 클릭했을때 페이지가 바뀌는 것을 막아주었고 그 함수를 여기에서 호출해주면 되는데 이것을 this.props.onChangePage()를 불렀다.

onChangePage={function(){
            alert('hihihi');
          }.bind(this)}

이것이 파일로 넘어와서 다음과 같이 실행되는 함수가 될 것이다.

this.props.onChangePage();

그래서 웹에서 WEB을 클릭했을시 경고창이 뜬것을 볼 수 있다.
이걸을 통해서 우리는 this.setState의 mode 값을 변경해주면 App이라고 하는 component에 welcome으로 바뀌는 것을 볼 수 있다. 쿨한데?

return (
      <div className="APP">
        <Subject title = {this.state.Subject.title} 
        sub={this.state.Subject.sub}
          onChangePage = {function(){
            this.setState({mode:'welcome'});
          }.bind(this)}
          ></Subject>

이번에는 글 목록을 클릭했을때 App이라고 하는 Component에 state 모드를 read로 바꾸고 클릭하는것이 본문에 나오게 할 것이다.

profile
The Known is finite The unknown is infinite.

0개의 댓글