React Basic Concept 02

Jungyub Song·2020년 5월 17일
0

1. React 컴포넌트의 Lifecycle

render, componentDidMount, componentDidUpdate, componentWillUnmount 등의 함수는 React.Component class에서 제공하는 메서드이다.

컴포넌트를 만들 때 class로 생성하면 위의 메서드를 사용할 수 있고, 컴포넌트가 lifecycle에 따라 각자의 메서드가 호출된다.

class Clock extends React.Component {

  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
  • ReactDOM.render()에서 첫 인자로 <Clock / >을 넘길 때, React는 Clock 컴포넌트의 constructor를 호출한다.
  • Clock에서 초기 시간이 필요하므로 this.state에 현재 시간으로 초기화한다.
  • 그 후에 Clock 컴포넌트의 render() 메서드가 호출된다.
  • DOM에서 render()의 return된 요소가 추가되면 componentDidMount 함수가 호출 된다.
  • Clock 컴포넌트의 tick 메서드가 매 초 호출될 수 있도록 timer를 추가한다.
  • 매 초 브라우저가 tick 메섣드를 호출하면서 this.state.date 값이 변한다.
  • state가 변경되면 원래 componentDidUpdate 함수가 호출되지만, 위에서 정의하지 않았으므로 render()가 다시 호출되면서 바뀐 부분이 변경된다.
  • DOM에서 Clock 컴포넌트가 삭제될 때, componentWillUnmount가 호출되고 timer도 같이 멈추게 된다.

2. Event Handling

class Button extends React.Component {

  constructor() {
    super();

    this.state = {
      clicked: false
    }

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({
      clicked: !this.state.clicked
    });
  }

  render() {
    return (
      <div
        className={`btn ${this.props.type === 'like' ? 'like-btn' : ''}`}
        onClick={this.handleClick}
      >
        {this.state.clicked ? '좋아요' : '싫어요'}
      </div>
    );
  }
}

ReactDOM.render(
  <Button type="like" />,
  document.getElementById('root')
);

Button 컴포넌트에 handleClick 메서드를 추가했고, onClick 이벤트에 this.handleClick event handler 함수를 넘겨주었다.
즉, 클릭할 때마다 this.state.clicked 값이 반대의 boolean 값으로 clicked state를 업데이트한다.

0개의 댓글