3주차 : 함수형 컴포넌트와 클래스형 컴포넌트

Milk717·2022년 11월 21일
0

AppCenter Web Study

목록 보기
2/3

1. 컴포넌트를 만드는 두 가지 방법

클래스형 컴포넌트

  • 현재는 거의 사용하지 않음.
  • 옛날 자료를 보면 발견할 수 있다.
  • 메모리 자원을 함수형 컴포넌트보다 조금 더 사용한다
  • state와 생명주기 관련 메소드가 있다.

함수형 컴포넌트

  • state와 생명주기 관련 메소드가 없지만 React Hook을 통해 동일 한 기능을 구현할 수 있다.
  • 메모리 자원을 함수형 컴포넌트보다 덜 사용한다.

클래스형 컴포넌트 코드

class Clock extends React.Component {
  constructor(props) {
    super(props);
    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>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

https://codepen.io/gaearon/pen/amqdNr?editors=0010

  • 메서드 호출 순서
    1. Clock 컴포넌트가 root.render()로 전달되었을 때 constructor가 호출되고 현재 시각이 업데이트 된다.
    2. 그 다음으로 Clock 컴포넌트의 render() 메서드가 호출된다. 이를 통해 DOM이 업데이트 된다.
    3. Clock 출력값이 DOM에 삽입되면 componentDidMount 메서드가 호출된다. 그 안에서 setInterval을 통해 1초마다 tick() 메서드가 호출되게 된다.
    4. Clock 컴포넌트가 DOM에서 삭제될 때 componentWillUnmount 메서드가 호출되고 타이머가 멈추게 된다.

함수형 컴포넌트 코드

function Clock(){
  const [state, setState] = React.useState({date: new Date()});
  const [timerId, setTimerId] = React.useState();
  
  React.useEffect(() => {
    setTimerId(setInterval(()=>tick(), 1000))
    return () => {
      clearInterval(timerID);
    }
  }, []);
  
  function tick(){
    setState({date: new Date()})
  }

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

https://codepen.io/milk717/pen/jOxRqby

2. 이벤트 핸들링

function Clock(){
  const [state, setState] = React.useState({date: new Date()});
  const [timerId, setTimerId] = React.useState();
  const [count, setCount] = React.useState(0);
  const [input, setInput] = React.useState(0);
  
  React.useEffect(() => {
    setTimerId(setInterval(()=>tick(), 1000))
    return () => {
      clearInterval(timerID);
    }
  }, []);
  
  function tick(){
    setState({date: new Date()})
  }
  
  const handleCountButtonClick = () =>{
    setCount(count + 1);
  }
  
  const handleCountReset = () =>{
    setCount(0);
  }
  
  const handleCount = (e, number) =>{
    console.log(number)
    setCount(number);
  }
  
  const handleChangeInput = (e) =>{
    setInput(Number(e.target.value));
  }

  return(
    <div>
        <h1>Hello, world!</h1>
        <h2>It is {state.date.toLocaleTimeString()}.
        </h2>
        <p>{count}</p>
        <button onClick={handleCountButtonClick}>count 증가</button>
        <button onClick={handleCountReset}>count 초기화</button>
        <button onClick={(e) =>handleCount(e, count-1)}>count 감소</button>
        <br/>
        <input type="number" onChange={handleChangeInput}/>
        <button onClick={(e) =>handleCount(e, input)}>count 입력</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

https://codepen.io/milk717/pen/poVByxL?editors=1011

과제

  • 저번주 과제를 컴포넌트별로 분리해서 만들기

0개의 댓글