React注册倒计时功能的实现

一、React版本

16.4.1

二、具体代码如下

设置state属性

rush:js;"> constructor(props){ super(props); this.state = { btnText:'获取验证码',seconds: 60,//称数初始化 liked: true //获取验证码文案 } }

2.倒计时

{ let siv = setInterval(() => { this.setState({ liked:false,seconds:this.state.seconds - 1,},() => { if(this.state.seconds == 0){ clearInterval(siv); this.setState({ liked:true,secounds:60 }) } }); },1000); }

3.jsx代码

rush:js;"> {getFieldDecorator('captcha',{ rules: [{ required: true,message: '请输入短信验证码!' }],})( )}

明明很简单的,但是看网上有的代码搞得很复杂一样,当然也可以用react相关插件,不过我觉得这样更简洁。

ps:react 获取服务器端时间倒计时

export default class Timer extends Component {

constructor(props) {
super(props)
this.state = {
bool: false,days: '0',hours: '00',minutes: '00',seconds: '00'
}
}

componentDidMount() {
this.start()
}

async start() {
this.timer && clearTimeout(this.timer) // 先清除一遍定时器,避免被调用多次
// 发起任意一个服务器请求, 然后从headers 里获取服务器时间
let leftTime = await axios.get('/').then(response => {
return new Date(this.props.date).getTime() - new Date(response.headers.date).getTime() // 服务器与倒计时的 时间差
}).catch(error => {
console.log(error)
return 0 // 这里发送的服务器请求失败 设为0
})

// 倒计时
this.timer = setInterval(() => {
leftTime = leftTime - 1000
let { bool,days = '0',hours = '00',minutes = '00',seconds = '00' } = this.countdown(leftTime)
if (bool) { // 结束倒计时
clearTimeout(this.timer)
}
this.setState({
bool,days,hours,minutes,seconds
})
},1000)
}

/**

  • 倒计时
  • @param leftTime 要倒计时的时间戳
    */
    countdown(leftTime) {
    let bool = false
    if (leftTime <= 0) {
    bool = true
    return { bool }
    }
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24,10) //计算剩余的天数
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24,10)
    if (hours < 10) {
    hours = '0' + hours
    }
    var minutes = parseInt(leftTime / 1000 / 60 % 60,10)
    if (minutes < 10) {
    minutes = '0' + minutes
    }
    var seconds = parseInt(leftTime / 1000 % 60,10)
    if (seconds < 10) {
    seconds = '0' + seconds
    }
    return { bool,seconds }
    }

componentwillUnmount() {
clearTimeout(this.timer)
}

render() {
let { bool,seconds } = this.state
return (

{ bool ?
活动已结束
:
{days} 天 {hours} : {minutes} : {seconds}
}
) } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...