[React] Event

hyeonze·2021년 12월 13일
0

React에서 Event가 처리되는 과정

  1. 이벤트발생
  2. App컴포넌트의 state변경
  3. 변경된 state가 자식컴포넌트의 props로 전달

state변경 -> App컴포넌트의 render함수 재호출 -> 자식컴포넌트들의 render함수들 재호출

React에서 이벤트 등록

<header>
  <h1><a href="/" onClick={function(e){
    e.preventDefault();
  }}>{this.state.subject.title}</a></h1>
</header>

이벤트로 state 변경

1.이벤트 등록 후 .bind(this)해줘야 함수 내에서 this사용가능
2.state를 변경할 때는 setState함수를 사용해야 브라우저가 인식함

<header>
  <h1><a href="/" onClick={function(e){
    e.preventDefault();
    // this.state.mode = 'welcome';
    this.setState({
      mode:'welcome'
    });
  }.bind(this)}>{this.state.subject.title}</a></h1>
</header>

bind함수

첫 매개변수 : 함수 내에서 this를 지정해줌

let obj = {name:'egoing'};
let bindTest = () => {
  console.log(this.name);
}
bindTest(); // undefined

let bindTest2 = bindTest.bind(obj); // obj를 this로하는 bindTest함수
bindTest2(); // egoing

둘째 이후 매개변수 : 함수 내에서 쓸 인자 지정(기존 인자는 한칸씩 뒤로감)

props에 함수 저장 후 사용하기

// 부모컴포넌트(props에 함수 저장)
<div className="App">
  <Subject
    title={this.state.subject.title}
    sub={this.state.subject.sub}
    onChangePage={function(){
      this.setState({mode:'welcome'});
    }.bind(this)}
  >
  </Subject>
  <TOC></TOC>
  <Content title="HTML" desc="HTML is HyperText Markup Language."></Content>
</div>

// 자식컴포넌트(props에 있는 함수 사용)
<header>
  <h1><a href="/" onClick={function(e){
    e.preventDefault();
    this.props.onChangePage();
  }.bind(this)}>{this.state.subject.title}</a></h1>
</header>

클릭이벤트 복습 및 재구현 해보기

profile
Advanced thinking should be put into advanced code.

0개의 댓글

관련 채용 정보