javascript - React App 中的倒计时似乎呈指数级倒计时
问题描述
我正在尝试使用 React JS 制作一个简单的倒计时按钮。它几乎完成了,但是,当我希望它只在单击按钮后才开始倒计时时,它会立即倒计时。
默认值为 10。如果不输入自己的值,大于 0,则从 10 开始倒计时。
下面是我的代码:
import React, {Component} from 'react';
import './app.css';
import { Form, FormControl, Button } from 'react-bootstrap';
class Countdown extends Component {
constructor(props){
super(props);
this.state={
time: ''
}
}
componentWillMount(){
this.setState({time: 10});
}
componentDidMount(){
setInterval(() => this.registerTime(this.state.time - 1), 1000);
}
registerTime(time){
if(time >= 0){
this.setState({time});
}
}
countdown(){
const textVal = document.getElementById('time-input').value;
if(isNaN(textVal) || textVal == '' || textVal == ' ' || textVal <= 0){
alert("Please enter a numeric value greater than 0!");
} else{
this.registerTime(textVal);
}
}
render(){
return(
<div className="app">
<h1>This is going to be a Countdown!</h1>
<div>{this.state.time}</div>
<Form inline>
<FormControl
id="time-input"
placeholder="new time"
onChange={event => {
if(event.target.value != '' && event.target.value != ' '){
this.setState({time: event.target.value});
}
}}
onKeyPress={event => {
if(event.key === 'Enter'){this.countdown();}
}}
/>
<Button onClick={event => this.countdown()} >Start</Button>
</Form>
</div>
);
}
}
export default Countdown;
解决方案
安装组件时,您已立即开始间隔。我已经为您创建了一个工作演示codepen
。
https://codepen.io/RutulPatel7077/pen/yRpzVB
推荐阅读
- java - 对于每个循环添加所有人口
- python - 从字典中提取数据
- java - 调用嵌套recyclerview适配器获取数据
- node.js - 如何在 index.js 文件中为 firebase-auth 提供服务密钥文件的路径?
- javascript - 如何在angularjs中创建一个简单的if then else?
- android - IllegalStateException:当我第二次尝试显示 AlertDialog 时
- go - 解析具有深层结构和数组值的 yaml
- asp.net-core - Azure SignalR 服务 - 多服务器配置
- lit-element - LitElement - 如果在 LitElement 渲染方法中的表达式,如何使用 javascript 创建 dom-if 重新标记行为?
- c++ - 访问“父”或“所有者”函数 C++