react倒计时功能

目录

类组件写法

函数组件写法:

[demo: 手机获取验证码登录(验证码60秒倒计时)](#demo: 手机获取验证码登录(验证码60秒倒计时))


react倒计时5 秒

React中的倒计时可以通过使用setInterval()函数来实现。下面是一个示例代码:

类组件写法

javascript 复制代码
import React from 'react';
import { Button } from 'antd';

class A extends React.PureComponent {

    constructor(props){
        super(props)
        this.state = {
           count: 0, // 初始值0
        }
    }
    clickCountTime = () => {
        this.setState({
            count: 5, // 设置一个5秒倒计时 
        })
        let timer = null;
        timer = setInterval(() => {
            this.setState({
                count: this.state.count - 1, // 倒计时减1秒 
            }, () => {
                if(this.state.count < 1) {
                    clearInterval(timer); // 清除定时器
                }
            })
        }, 1000)
    }
    
    render () {
        const { count } = this.state;
        return (
            <Button 
                type='primary'
                style={{ width:'85px' }}
                disabled={!!count} // 倒计时期间不可编辑,如果count=0,0是false,!0=true, !!0=false
                onClick={this.clickCountTime}
            >
                {count === 0 ? '获取验证码' : `${count}秒后重试`}
            </Button>
        )
    }

}

export default A

react倒计时60 秒

React中的倒计时可以通过使用setInterval()函数来实现。下面是一个示例代码:

函数组件写法:

设置一个button按钮给点击事件,按下后状态变为disabled,开始定时器每秒减一,当时间为0时,清除定时器,重置会原来的状态。

javascript 复制代码
import React, { useState, useEffect, useCallback, useRef } from 'react';

const CountDown () {
  
  const intervalRef = useRef(null); // 使用useRef来存储计数器的值,并在setInterval函数中访问它
  
  const [count, setCount] = useState(0); // 初始值count=0
  
  // 组件卸载时清除计时器:设置清除定时器,避免count还未为0时,组件已被Unmount
  useEffect(() => {
    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

    // 监听count的变化 
  useEffect(() => {
    if (count === 59) {
      intervalRef.current = setInterval(() => {
        setCount((preCount) => preCount - 1);
      }, 1000);
    } else if (count === 0) {
      clearInterval(intervalRef.current);
    }
  }, [count]);

    // 点击事件
  const onGetCaptcha = useCallback(() => {
    setCount(59); // 从59秒开始倒计时
  }, []);

  return (
    <Button type='button' disabled={!!count} onClick={onGetCaptcha}>
        {count ? `${count} s` : '获取验证码'}
    </Button>
  );
};

export default CountDown;

demo: 手机获取验证码登录(验证码60秒倒计时)

javascript 复制代码
import { Row, Col, Input, Button } from "antd"
import { useState, useRef, useEffect } from "react"

const InputGroup = Input.Group;

const App = () => {

  const [phone, setPhone] = useState(null); // 定义初始手机号
  const [count, setCount] = useState(0) // 默认0秒
  const timerRef = useRef(null) // 使用useRef设置一个倒计时器,这样我就可以防止重新渲染

   // 监听count的变化 
  useEffect(() => {
    if (count === 59) {
      intervalRef.current = setInterval(() => {
        setCount((preCount) => preCount - 1);
      }, 1000);
    } else if (count === 0) {
      clearInterval(intervalRef.current);
    }
  }, [count]); // count改变就会执行


    // 获取验证码
    const getInfo = () => {
        const reg= /^1[3456789]\d{9}$/;
        if(phone !== null || phone !== underfine) {
            if(!reg.test(phone )) { // 若手机号不符合要求,倒计时不进行
                setCount(0);
                message.error('输入的手机号不正确!')
                return false;
            } else {
                // 调接口,传给后台,获取后台的status状态
                axios.post('', { phone }).then(res => {
                    if(status.success === false) {
                        setCount(0);
                        message.error('发送失败!')
                    } else {
                        message.success ('发送成功!')
                        setCount(59);
                    }
                })
            }
        }


    // 获取手机号输入框里的值    
    const getValue = (e) => {
        setPhone(e.target.value);
    }


  return (
    <div>
       <p>手机号</p>
        <Row>
         <Col span={8}>
            <Input placeholder='请输入手机号' onBlur={e => getValue(e)} allowClear />
         </Cow>
       </Row>
       <p>短信验证码</p>
       <Row>
         <Col span={8}>
            <InputGroup compact>
                <Input placeholder='请输入验证码' style={{ width: '40%'}} allowClear />
                <Button onClick={getInfo} disabled={!!count}>{count === 0 ? '获取验证码': `${count}秒后重发`}</Button>
            </InputGroup>
         </Cow>
       </Row>
   </div>
  )
}

export default App
相关推荐
涛涛ing几秒前
2026年,前端框架开始为 AI 而生了
前端
2603_965896625 分钟前
DOM文档对象模型|JS操作页面交互核心API
前端·javascript
骇客野人15 分钟前
Java 前后端可部署落地架构方案
服务器·前端·微服务
OpenTiny社区21 分钟前
从开发到运行:OpenTiny NEXT 如何构建 Agent 时代的 Web 应用
前端·开源·ai编程·opentiny
feixing_fx26 分钟前
伪类与伪元素的魔法:纯 CSS 打造炫酷的按钮悬停特效
前端·css·css3
动恰客流统计27 分钟前
用客流数据优化门店排班:高峰不缺人、平峰不浪费的落地路径
大数据·前端·人工智能
广州山泉婚姻36 分钟前
前后端分离的核心优势
前端·后端
志尊宝37 分钟前
Vue3 零基础每日笔记(043):defineModel 与 defineExpose 的 TS 用法——3.4+ 新 API 进阶
前端·javascript·vue·html·vue3
洛兮银儿38 分钟前
前端页面引入cesium
前端·cesium
SEO_juper1 小时前
2026年用Python分析网站访问日志:看清Googlebot和AI爬虫怎么爬你的站(附完整代码)
开发语言·前端·seo·独立站·谷歌优化