2022-05-31 学习记录--React-实现60s倒计时

React-实现60s倒计时

当我们点击“获取验证码”后,文字变成60s倒计时(隔1s,秒数-1),当秒数为0s时,文字又变回“获取验证码”。❀

class HomePage extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
  }

  initValue = 60 // 定义倒计时秒数

  state = {
    
     // 定义state初始化数据
    timer: this.initValue, // 倒计时数
  }

  // 点击“获取验证码”
  getCode = () => {
    
       
      this.setState({
    
    
        isClick: true, // true->显示 倒计时秒数;false->显示 “开始倒计时”
      })
      let auth_timer = setInterval(() => {
    
    
        // 定时器设置每秒递减
        const new_timer = this.state.timer-1; // 递减时间
        this.setState({
    
    
          timer: new_timer,
        }) 
        if (this.state.timer <= 0) {
    
    
          this.setState({
    
    
            isClick: false, // true->显示 倒计时秒数;false->显示 “开始倒计时”
          })
          clearInterval(auth_timer); // 清除定时器
          this.setState({
    
    
            timer: this.initValue, // 将秒数恢复到初始数据
          }) 
        }
      }, 1000)
  }
  
  render() {
    
    
    return (
      <div>
       {
    
    
          this?.state?.isClick?
          <span>{
    
    this.state.timer}s</span>:
          <span onClick={
    
    this.getCode}>获取验证码</span>
        }
      </div>
    );
  }
}  

猜你喜欢

转载自blog.csdn.net/weixin_48850734/article/details/125059958
今日推荐