react倒计时功能

 

目录

类组件写法

函数组件写法:

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


react倒计时5 秒

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

类组件写法

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时,清除定时器,重置会原来的状态。



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秒倒计时)

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
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值