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
相关推荐
大怪v1 天前
【Virtual World 04】我们的目标,无限宇宙!!
前端·javascript·代码规范
狂炫冰美式1 天前
不谈技术,搞点文化 🧀 —— 从复活一句明代残诗破局产品迭代
前端·人工智能·后端
xw51 天前
npm几个实用命令
前端·npm
!win !1 天前
npm几个实用命令
前端·npm
代码狂想家1 天前
使用openEuler从零构建用户管理系统Web应用平台
前端
dorisrv1 天前
优雅的React表单状态管理
前端
蓝瑟1 天前
告别重复造轮子!业务组件多场景复用实战指南
前端·javascript·设计模式
dorisrv1 天前
高性能的懒加载与无限滚动实现
前端
韭菜炒大葱1 天前
别等了!用 Vue 3 让 AI 边想边说,字字蹦到你脸上
前端·vue.js·aigc
StarkCoder1 天前
求求你,别在 Swift 协程开头写 guard let self = self 了!
前端