【问题标题】:Create Countdown Timer创建倒数计时器
【发布时间】:2019-07-10 22:33:51
【问题描述】:

我想在 React Js 中创建一个倒计时计时器,我将在其中用户开始(开始倒计时)、停止(停止倒计时)和重置(重置计时器),如图例所示。

作为我在 React JS 和全局 javascript 中的初学者开发人员,我首先测试按钮。之后我创建了一个函数“secondPass”来计算剩余时间,然后显示它。“countDown”变量用于停止之后的“setinterval”与“clearInterval(countDown)”。

问题是我在“codesandbox”平台中收到错误消息,如图所示。如果有人能解释我的错误,如果不是太多要求帮助我编写一个非常简单的代码来实现我的项目。

这里是 React 代码:

import React from "react";

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      timer: 90
    };
  }

  var seconds = 1200, // Number Of Seconds

  countDown = setInterval(function() {
    secondPass();
  }, 1000);

  function secondPass() {

  var minutes = Math.floor(seconds / 60),  // To Determine The Minutes 

  var remSeconds = seconds % 60;   // To Determine The Seconds

}

  resetTime() {
    this.setState({ timer: 0 });
  }
  render() {
    const { timer } = this.state;
    return (
      <div className="App">
        <h2>{timer}</h2>
        <button onClick={() => this.resetTime()}>Reset</button>
      </div>
    );
  }
}

【问题讨论】:

  • 什么是倒计时?您需要使用关键字对其进行初始化。尝试将 let 放在 countDown = ... 之前
  • 您有一些语法错误。基本上,您不能按照您的方式定义变量 (seconds) 和方法,这是错误的语法。您可能会发现此链接很有用developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 在定义secondPass() 方法时尝试不使用function 关键字。

标签: javascript reactjs


【解决方案1】:

这是因为secondPass 是在Timer 类的主体中定义的成员函数。在 JS 中,前面不需要function,就像渲染一样声明:将function secondPass 更改为secondPass

【讨论】:

    【解决方案2】:

    在类中为 secondPass 函数声明函数时,不需要使用 function 关键字。这是新的 ES6 语法。

    【讨论】:

      【解决方案3】:

      删除secondPass 函数的function 关键字。如果在类中声明函数,则不需要 function 关键字。

      让它像,

      export default class Timer extends React.Component {
        constructor(props) {
          super(props);
      
          this.state = {
            timer: 90
          };
        }
      
        var seconds = 1200, // Number Of Seconds
      
        countDown = setInterval(function() {
          secondPass();
        }, 1000);
      
        secondPass() {
      
          var minutes = Math.floor(seconds / 60),  // To Determine The Minutes 
      
          var remSeconds = seconds % 60;   // To Determine The Seconds
      
        }
      
        resetTime() {
          this.setState({ timer: 0 });
        }
        render() {
          const { timer } = this.state;
          return (
            <div className="App">
              <h2>{timer}</h2>
              <button onClick={() => this.resetTime()}>Reset</button>
            </div>
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-13
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多