• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

저.. 왜 리셋버튼이 작동을 안할까요?

20.07.26 00:47 작성 조회수 105

0

import React, { Component } from 'react';

class ResponseCheck extends Component {
  state = {
    state: 'waiting',
    message: '클릭해서 시작하세요.',
    result: [],
  };

  timeout;
  startTime;
  endTime;

  onClickScreen = () => {
    const { state } = this.state;
    if (state === 'waiting') {
      timeout.current = setTimeout(() => {
        this.setState({
          state: 'now',
          message: '지금 클릭',
        });
        this.startTime = new Date();
      }, Math.floor(Math.random() * 1000) + 2000); // 2초~3초 랜덤
      this.setState({
        state: 'ready',
        message: '초록색이 되면 클릭하세요.',
      });
    } else if (state === 'ready') { // 성급하게 클릭
      clearTimeout(this.timeout);
      this.setState({
        state: 'waiting',
        message: '너무 성급하시군요! 초록색이 된 후에 클릭하세요.',
      });
    } else if (state === 'now') { // 반응속도 체크
      endTime.current = new Date();
      this.setState((prevState=> {
        return {
          state: 'waiting',
          message: '클릭해서 시작하세요.',
          result: [...prevState.resultthis.endTimethis.startTime],
        };
      });
    }
  };

  onReset = () => {
    this.setState({
      result: [],
    });
  };

  renderAverage = () => {
    const {result} = this.state;
    return result.length === 0
      ? null
      : <>
        <div>평균 시간: {result.reduce((ac=> a + c) / result.length}ms</div>
        <button onClick={this.onReset}>리셋</button>
      </>
  };

  render() {
    const { statemessage } = this.state;
    return (
      <>
        <div
          id="screen"
          className={state}
          onClick={this.onClickScreen}
        >
          {message}
        </div>
        {this.renderAverage()}
      </>
    )
  }
}

export default ResponseCheck;
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>game</title>
    </head>
    <style>
        #screen {
            width300px;
            height200px;
            text-aligncenter;
            user-selectnone;
        }
        #screen.waiting {
            background-color#5a985c;
        }
        #screen.ready {
            background-color#dc7171;
            colorwhite;
        }
        #screen.now {
            background-color#acd674;
        }
    </style>
    <body>
        <div id="root"></div>
        <script src="./dist/app.js"> 
        </script>
    </body>
</html>

답변 1

답변을 작성해보세요.

1

onReset 안에 콘솔로그를 넣어 onReset 함수 자체가 실행되는지 체크해보세요.