728x90
반응형

사용자와 상호작용하는 컴포넌트 만들기

Square 컴포넌트를 클릭하면 “X”가 체크되도록 만들어보자

먼저 Square 컴포넌트의 render() 함수에서 반환하는 버튼 태그를 아래와 같이 변경하기

class Square extends React.Component {
  render() {
    return (
      <button className="square" onClick={function() { console.log('click'); }}>
        {this.props.value}
      </button>
    );
  }
}

Square를 클릭하면 ‘click’이 브라우저 개발자 도구의 콘솔에 출력되는 걸 확인할 수 있음

주의

타이핑 횟수를 줄이고 this의 혼란스러운 동작을 피하기 위해 아래부터는 이벤트 핸들러에 화살표 함수를 사용할 것임

class Square extends React.Component {
 render() {
   return (
     <button className="square" onClick={() => console.log('click')}>
       {this.props.value}
     </button>
   );
 }
}

onClick={() => console.log('click')}이 어떻게 동작하는지 살펴보면 onClick prop으로 함수를 전달하고 있음
React는 클릭했을 때에만 이 함수를 호출할 것임
() =>을 잊어버리고 onClick={console.log('click')}이라고 작성한다면 컴포넌트가 다시 렌더링할 때마다 경고 창이 뜰 것임

 

다음 단계로 Square 컴포넌트를 클릭한 것을 “기억하게” 만들어 “X” 표시를 채워 넣으려고 합니다. 무언가를 “기억하기”위해 component는 state를 사용

React 컴포넌트는 생성자에 this.state를 설정하는 것으로 state를 가질 수 있음

this.state는 정의된 React 컴포넌트에 대해 비공개로 간주해야 함

이제 Square의 현재 값을 this.state에 저장하고 Square를 클릭하는 경우 변경할 것임

우선 클래스에 생성자를 추가하여 state를 초기화하기

class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }
  
  render() {
    return (
      <button className="square" onClick={() => console.log('click')}>
        {this.props.value}
      </button>
    );
  }
}

주의

JavaScript 클래스에서 하위 클래스의 생성자를 정의할 때 항상 super를 호출해야 함
모든 React 컴포넌트 클래스는 생성자를 가질 때 super(props) 호출 구문부터 작성해야 함

이제 Square를 클릭할 때 현재 state 값을 표시하기 위해 render 함수를 변경할 것임

  • <button> 태그 안 this.props.value를 this.state.value로 변경하기
  • onClick={...} 이벤트 핸들러를 onClick={() => this.setState({value: 'X'})}로 변경하기
  • 가독성을 높이기 위해 className과 onClick props를 별도의 줄에 넣기

이와 같은 변경 후에 Square의 render 함수에서 반환하는 <button> 태그는 아래의 형태와 같음

class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }

  render() {
    return (
      <button
        className="square"
        onClick={() => this.setState({value: 'X'})}
      >
        {this.state.value}
      </button>
    );
  }
}

Square의 render 함수 내부에서 onClick 핸들러를 통해 this.setState를 호출하는 것으로 React에게 <button>을 클릭할 때 Square가 다시 렌더링해야 한다고 알릴 수 있음
업데이트 이후에 Square의 this.state.value는 'X'가 되어 게임 판에서 X가 나타나는 것을 확인할 수 있음
어떤 Square를 클릭하던 X가 나타날 것임

컴포넌트에서 setState를 호출하면 React는 자동으로 컴포넌트 내부의 자식 컴포넌트 역시 업데이트함

 

지금까지의 전체 코드 확인하기

 


참고 자료 : https://ko.reactjs.org/tutorial/tutorial.html#making-an-interactive-component

 

자습서: React 시작하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

반응형
복사했습니다!