JavaScript/React.js

[React.js] 이벤트 처리

aaaahy 2023. 2. 7. 16:31

 

애플리케이션을 역동적으로 만들어주는 이벤트 만들기

 

*참고

React에서 컴포넌트 안의 render() 함수는 props 값이나 state 값이 바뀌면 다시 호출되어 화면이 그려진다.

 

※ 자세한 내용참고

https://ko.reactjs.org/docs/handling-events.html

 

이벤트 처리하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

React에서의 이벤트 처리 사용 예제

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

▷ Subject.js 파일의 Subject 컴포넌트

▶ JSX를 사용하여 함수로 이벤트 핸들러 전달

▶ e.preventDefault(); → 이벤트 기본적인 동작(reload되는것) 막기

 

 

이벤트에서 state 값 변경하기

- 이벤트가 호출됐을 때, 실행되는 함수 안에서 this.state 값 변경 불가능

→ 어떤 this를 가리키는지 몰라서 state 값이 undefined

 

해결

- setState()와 bind() 활용

class App extends Component {
  constructor(props){ 
    super(props);
    this.state = {
      mode:'read',
      selected_content_id:2,
      subject:{title:'WEB', sub:'World Wide Web!'},
      welcome:{title:'Welcome', desc:'Hello, React!!!'},
      contents:[
        {id:1, title:'HTML', desc:'HTML is for information'},
        {id:2, title:'CSS', desc:'CSS is for design'},
        {id:3, title:'JavaScript', desc:'JavaScript is for interactive'}
      ]
    }
  }
  render() { // 어떤 html을 그릴지 결정, props나 state 값이 바뀌면 해당되는 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'){
      var i = 0;
      while(i < this.state.contents.length){
        var data = this.state.contents[i];
        if(data.id === this.state.selected_content_id){
          _title = data.title;
          _desc = data.desc;
          break;
        }
        i= i + 1;
      }
      
    }
    // console.log(this); // render() 함수 안에서의 this는 속해있는 해당 컴포넌트 가리킴(App)
    return (
      <div className="App">
        <Subject 
          title={this.state.subject.title}
          sub={this.state.subject.sub}
          onChangePage = {function(){
            this.setState({mode:'welcome'});
          }.bind(this)} 
        >
        </Subject>
      </div>
    );
  }
}

▷ App.js

▶ Subject 태그의 props 값으로 onChangePage 작성 → state 값 변경

▶ this.setState()로 state의 mode 값 변경 + bind(this) 

 

 

bind() 이해하기

var obj = {name:'aaaahy'};

function bindTest() {
	console.log(this.name);
}

bindTest(); // 결과 undefined

var bindTest2 = bindTest.bind(obj);
bindTest2(); // 결과 aaaahy

▶ bindTest(); 결과 함수 안에서의 this 값을 모르므로 undefined

▶ bind() 사용시 bindTest()의 함수 안에서의 this는 obj를 의미 → 결과 aaaahy

 

 

이벤트 사용하기

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>
      );
    }
}

▷ Subject.js

▶ 해당 부분(a태그)을 클릭했을 경우, onChangePage 함수(state 값 변경하는 함수) 호출

 

* 생활코딩 React-16.1, React-16.2, React-16.3, React-16.4, React-17.1 강의 기반으로 작성됨

'JavaScript > React.js' 카테고리의 다른 글

[React.js] 컴포넌트 State  (0) 2023.02.02
[React.js] 컴포넌트(Component) 만들기  (0) 2023.01.31