以下是一个实现这个功能的示例代码:

import React from 'react';

class Countdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 60,  // 初始倒计时时间
      disabled: false  // 按钮是否为禁用状态
    };
  }

  componentDidMount() {
    this.startCountdown();
  }

  startCountdown() {
    this.timer = setInterval(() => {
      this.setState(prevState => ({
        count: prevState.count - 1
      }), () => {
        if (this.state.count === 0) {
          this.resetCountdown();
        }
      });
    }, 1000);
  }

  resetCountdown() {
    clearInterval(this.timer);
    this.setState({
      count: 60,
      disabled: false
    });
  }

  handleClick() {
    // 需要调用发送验证码的函数,此处只是一个示例
    sendVerificationCode()
      .then(() => {
        this.setState({ disabled: true });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    const { count, disabled } = this.state;
    return (
      <div>
        <button onClick={() => this.handleClick()} disabled={disabled}>
          {disabled ? `${count}秒` : '获取验证码'}
        </button>
      </div>
    );
  }
}

// 示例发送验证码的函数
function sendVerificationCode() {
  return new Promise((resolve, reject) => {
    // 模拟发送验证码的操作,这里使用setTimeout来模拟异步请求
    setTimeout(() => {
      resolve();
    }, 1000);
  });
}

export default Countdown;

在上述代码中,Countdown 组件包含一个按钮,点击按钮后会调用 handleClick 函数,该函数会调用发送验证码的函数 sendVerificationCode。在 sendVerificationCode 函数中,使用 setTimeout 模拟了异步请求,当请求成功后会通过 resolve 回调函数来通知成功。在 handleClick 函数中,调用 sendVerificationCode 函数后,将按钮设置为禁用状态,并开始倒计时。

componentDidMount 生命周期函数中,调用 startCountdown 函数开始倒计时。startCountdown 函数使用 setInterval 来每秒减少倒计时时间,当倒计时时间达到 0 时,调用 resetCountdown 函数来重置倒计时。

render 函数中,根据按钮的禁用状态来显示倒计时时间或者获取验证码。

React 类组件实现 60 秒验证码倒计时功能

原文地址: https://www.cveoy.top/t/topic/pcrL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录