欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于React實現(xiàn)倒計時功能

 更新時間:2024年02月29日 09:10:20   作者:outstanding木槿  
這篇文章主要為大家詳細介紹了如何基于React實現(xiàn)倒計時功能,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考一下

react倒計時5 秒

React中的倒計時可以通過使用setInterval()函數(shù)來實現(xiàn)。下面是一個示例代碼:

類組件寫法

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, // 設(shè)置一個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()函數(shù)來實現(xiàn)。下面是一個示例代碼:

函數(shù)組件寫法

設(shè)置一個button按鈕給點擊事件,按下后狀態(tài)變?yōu)閐isabled,開始定時器每秒減一,當(dāng)時間為0時,清除定時器,重置會原來的狀態(tài)。

import React, { useState, useEffect, useCallback, useRef } from 'react';
 
const CountDown () {
  
  const intervalRef = useRef(null); // 使用useRef來存儲計數(shù)器的值,并在setInterval函數(shù)中訪問它
  
  const [count, setCount] = useState(0); // 初始值count=0
  
  // 組件卸載時清除計時器:設(shè)置清除定時器,避免count還未為0時,組件已被Unmount
  useEffect(() => {
    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);
 
    // 監(jiān)聽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設(shè)置一個倒計時器,這樣我就可以防止重新渲染
 
   // 監(jiān)聽count的變化 
  useEffect(() => {
    if (count === 59) {
      intervalRef.current = setInterval(() => {
        setCount((preCount) => preCount - 1);
      }, 1000);
    } else if (count === 0) {
      clearInterval(intervalRef.current);
    }
  }, [count]); // count改變就會執(zhí)行
 
 
    // 獲取驗證碼
    const getInfo = () => {
        const reg= /^1[3456789]\d{9}$/;
        if(phone !== null || phone !== underfine) {
            if(!reg.test(phone )) { // 若手機號不符合要求,倒計時不進行
                setCount(0);
                message.error('輸入的手機號不正確!')
                return false;
            } else {
                // 調(diào)接口,傳給后臺,獲取后臺的status狀態(tài)
                axios.post('', { phone }).then(res => {
                    if(status.success === false) {
                        setCount(0);
                        message.error('發(fā)送失敗!')
                    } else {
                        message.success ('發(fā)送成功!')
                        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}秒后重發(fā)`}</Button>
            </InputGroup>
         </Cow>
       </Row>
   </div>
  )
}
 
export default App

到此這篇關(guān)于基于React實現(xiàn)倒計時功能的文章就介紹到這了,更多相關(guān)React倒計時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論