首页 > 解决方案 > 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;

标签: javascriptreactjscomponents

解决方案


安装组件时,您已立即开始间隔。我已经为您创建了一个工作演示codepenhttps://codepen.io/RutulPatel7077/pen/yRpzVB


推荐阅读