본문 바로가기
FrontEnd/React.js

[React.js] 나의 this만 undefined가 아닌 이유

by Chaedie 2022. 8. 11.
728x90

리액트 클래스형 컴포넌트를 공부하고 있습니다.

위코드에서 함수형 컴포넌트를 기준으로 리액트를 배우는 중입니다. 그런데 자꾸 공부하면 할수록 클래스형 컴포넌트도 배워서 좀 더 리액트에 대해 잘 알고 싶다는 생각이 들었습니다. 공식문서를 보면 대부분이 클래스형 컴포넌트, 함수형 컴포넌트 2가지를 병행해서 설명해주고 있는데, 그것이 클래스형 컴포넌트를 기준으로 배운 사람을 위함일수도 있지만, 함수형 컴포넌트만으로는 설명이 안되는 부분이 있어서 일지도 모르겠다는 생각을 했거든요....

생활코딩에 클래스형 컴포넌트 리액트 강의를 보다가...

그래서 생활코딩 리액트 (클래스형 컴포넌트) 강의를 보고 있습니다. 그런데 강의에서 this바인딩에 대해 알려주는 부분에서 저의 this와 egoing님의 this가 다른 것을 참조한다는것을 확인했습니다. egoing님은 분명히 event Handler 함수 내에서는 this가 "undefined"로 뜬다고 보여주시는데, 저의 this는 Component를 참조하고 있었습니다.

도저히 이해가 안되어 이것저것 찾아보고 물어보고 했는데, 결국 항상 감사한 동기님께서 "모든것은 공식문서에 있습니다." 하면서 링크를 보내주었습니다.

리액트 공식 문서 : 이벤트 처리하기

위 링크를 보면 콜백에 화살표 함수를 사용하면 this가 컴포넌트를 지칭하게 되고, 이것이 event Handler에 bind(this)를 안해도 Component를 참조하도록 만들수 있다고 되어 있습니다.

저는 강의를 따라하면서 강사님과 똑같이 unction () {} 형식으로 함수를 만들지 않고, 저도 모르게 습관대로 Arrow Funciton 을 콜백함수로 넣으며 수업을 들었던게 강의속 this와 저의 this가 다른 원인이었습니다.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: 'read',
      welcome: { title: 'Welcome', desc: 'Hello, React!!' },
      subject: { title: 'WEB', sub: 'World wide web!' },
      contents: [
        { id: 1, title: 'HTML', desc: 'HTML is HyperText ...' },
        { id: 2, title: 'CSS', desc: 'CSS is for design' },
        { id: 3, title: 'JavaScript', desc: 'JavasScript is for interactive' },
      ],
    };
  }
  render() {
    console.log('render in', this);
    let _title = null;
    let _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">
        <header>
          <h1>
            <a
              href="/"
              onClick={event => {
                console.log('event in', this);
                event.preventDefault();
                this.setState({ mode: 'welcome' });
              }}
              // onClick={function (event) {
              //   console.log('event in', this);
              //   event.preventDefault();
              //   this.setState({ mode: 'welcome' });
              // }}
            >
              {this.state.subject.title}
            </a>
          </h1>
          {this.state.subject.sub}
        </header>
        {/* <Subject title={this.state.subject.title} sub="world Wide Web!"></Subject> */}
        <TOC data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );
  }
}

얼떨결에 this 바인딩을 하지 않아도 되는 해결책을 찾게 되어 좋아해야하나요? ㅎㅎ🤣🤣
오늘도 재밌게 개발하는 중입니다. 고수가 되는 그날까지 ~ 고고 🚀🚀

댓글