출처: https://www.codecademy.com

변수 선언 - let, cosnt

React에서의 변수 선언은 let, const을 사용한다.

const 로 선언된 변수는 다시 할당하거나 선언할 수 없으나, let 으로 선언된 변수는 변경 가능하다.

    
    // 불가능
    const hellowReact = 'Hello React1';
    hellowReact = 'Hello React2';
    
    //가능 
    let hellowReact = 'Hello React1';
    hellowReact = 'Hello React2';
    

컴포넌트 내에서 this 의 사용

React를 사용하다보면 this가 많이 눈에 띄일것이다.

자바스크립트에서의 this 와는 다른 컨셉으로 사용되는 리액트에서의 this 쓰임을 알아보자.

참고) React와 자바스크립트에서의 this 사용과 차이 : https://gist.github.com/amitai10/adb66d6faa714e8c3cdb94946bb98356

    class IceCreamGuy extends React.Component {
      get food() {
        return 'ice cream';
      }
    
      render() {
        return <h1>I like {this.food}.</h1>;
      }
    }

위 코드에서 this 는 무엇을 의미할까?

여기서 this 는 IceCreamGuy의 인스턴스를 가르킨다.

그러므로 this.food 는 ‘ice cream’ 로 보여지게 된다.


또한 getter 매서드는 괄호없이 this.food 로 사용한다. this.food()

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class MyName extends React.Component {
    	// name property goes here:
    	get name(){
        return 'THOR';
      }
    
      render() {
        return <h1>My name is {this.name}.</h1>;
      }
    }
    
    ReactDOM.render(<MyName />, document.getElementById('app'));

실행결과: 화면에 My name is THOR. 출력



컴포넌트 내에서 Event Listener 의 사용

React에서는 이벤트 핸들러를 컴포넌트 클래스 내에서 매서드로 선언할 수 있다.

예) scream() 이벤트 핸들러의 사용 - onClick

        import React from 'react';
        import ReactDOM from 'react-dom';
        
        class Button extends React.Component {
          scream() {
            alert('AAAAAAAAHHH!!!!!');
          }
        
          render() {
            return <button onClick={this.scream}>ClickMe!</button>;
          }
        }
        
        ReactDOM.render(<Button />, document.getElementById('app'))

실행결과: ClickMe! 라는 버튼 클릭 시, ‘AAAAAAAAHHH!!!!!’ 알림창 팝업