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
相关推荐
已读不回1431 分钟前
设计模式-工厂模式
前端·算法·代码规范
郭少1 分钟前
🔥 我封装了一个会“思考”的指令!Element-Plus Tooltip 自动检测文本溢出,优雅展示
前端·vue.js·性能优化
谢泽豪2 分钟前
解决 uniapp 修改index.html文件不生效的问题
前端·uni-app
袁煦丞2 分钟前
【黑科技指南】自托管私人导航站Dashy:cpolar内网穿透实验室第476个成功挑战
前端·程序员·远程工作
Nayana3 分钟前
Clean Code JavaScript小记(一)
javascript
heartmoonq5 分钟前
关于前端监控用户行为导致的报错
前端
已读不回1436 分钟前
告别痛苦的主题切换!用一个插件解决 Tailwind CSS 多主题开发的所有烦恼
前端·架构
pepedd8646 分钟前
🚀Webpack 从入门到优化,一文全掌握!
前端·webpack·trae
TimelessHaze7 分钟前
【面试考点】从URL输入到页面展示
前端·trae
玲小珑9 分钟前
LangChain.js 完全开发手册(一)AI 应用开发入门
前端·langchain·ai编程