【问题标题】:How to set OTP timer on button click in react JS?如何在 React JS 中单击按钮时设置 OTP 计时器?
【发布时间】:2022-07-08 21:00:20
【问题描述】:

问题:- 我制作了一个模式,我正在其中进行手机号码验证。我希望 OTP 计时器在单击 Send OTP 按钮时启动,但它没有发生。

我已使用 useeffect() 创建计时器,但这样,计时器开始在页面加载时运行,但我只希望计时器在单击 Send OTP 按钮时启动。我该怎么做?

我正在粘贴代码沙盒链接供您参考。请指导我。

代码:-https://codesandbox.io/s/goofy-hawking-wd1ze9

【问题讨论】:

标签: javascript reactjs react-hooks bootstrap-modal react-bootstrap


【解决方案1】:

倒计时从 ReactJs 中的按钮点击事件开始:

import React from 'react'
import { useState, useEffect } from 'react';

const Timer = (props:any) => {
    const {initialMinute = 0,initialSeconds = 0} = props;
    const [ minutes, setMinutes ] = useState(initialMinute);
    const [seconds, setSeconds ] =  useState(initialSeconds);
    useEffect(()=>{
    let myInterval = setInterval(() => {
            if (seconds > 0) {
                setSeconds(seconds - 1);
            }
            if (seconds === 0) {
                if (minutes === 0) {
                    clearInterval(myInterval)
                } else {
                    setMinutes(minutes - 1);
                    setSeconds(59);
                }
            } 
        }, 1000)
        return ()=> {
            clearInterval(myInterval);
          };
    });

    return (
        <div>
        { minutes === 0 && seconds === 0
            ? null
            : <h1> {minutes}:{seconds < 10 ?  `0${seconds}` : seconds}</h1> 
        }
        </div>
    )
}

export default Timer;

【讨论】:

  • 它不工作。此外,它没有任何点击事件,所以它只在页面加载时被调用。
【解决方案2】:

只需使用这个 sn-p,因为它还有助于记忆超时回调。

const [timer, setTimer] = useState(60);    
const timeOutCallback = useCallback(() => setTimer(currTimer => currTimer - 1), []);

useEffect(() => {
  timer > 0 && setTimeout(timeOutCallback, 1000);
}, [timer, timeOutCallback]);

console.log(timer);

const resetTimer = function () {
  if (!timer) {
    setTimer(60);
  }
};

在你的 JSX 中

<Text style={styles.textLogin} onPress={resetTimer}>Resend OTP ({timer})</Text>

希望这会对您或其他人有所帮助。

编码愉快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2020-12-01
    • 2016-12-16
    • 2014-02-28
    相关资源
    最近更新 更多