(1)可以通过使用“react-timer-mixin”插件实现倒计时效果,原理同下面的思路一样此处不在详细解说
(2)自己用原生定时器方法实现 1 import React,{Component} from ‘react‘; 2 import {Button } from ‘antd-mobile‘; 3 import PropTypes from ‘prop-types‘; 4 class SendVerifyCode extends Component{ 5 constructor(props){ 6 super(props) 7 this.state={ 8 count:0, 9 counting:false 10 } 11 } 12 componentWillReceiveProps(nextProps){ 13 //根据父组件传过来的验证结果,判断是否启用倒计时 14 if(nextProps.isSend){ 15 this.send(); 16 //发送完验证码成功之后,通知父组件关闭发送开关 17 nextProps.onSuccessSend() 18 } 19 } 20 setInterval=() => { 21 /*此处正是定时器运用的巧妙之处,以及对定时器返回值的理解程度体现 22 定时器必须在一个函数中赋值给一个属性,在state中赋值就不行,定时器会自执行, 23 因此必须在一个不会自动执行的函数中把定时器ID赋值给一个变量保存 24 此ID可以作为clearInterval()的参数,用于清除定时器*/ 25 this.timer = setInterval(this.countDown, 1000) 26 } 27 send=()=>{ 28 this.setState( { counting: true, count: 60}); 29 this.setInterval(); 30 } 31 countDown = () =>{ 32 const { count } = this.state; 33 if ( count === 1) { 34 this.clearInterval(); 35 this.setState( { counting: false }); 36 } else { 37 this.setState( { counting: true, count: count - 1}); 38 } 39 } 40 clearInterval=() =>{ 41 clearInterval(this.timer) 42 } 43 phone =() => { 44 //验证手机号是否符合规则,符合规则就设置props.isSend为true,启用定时器,否则提示错误信息 45 this.props.onhandlePhone() 46 //console.log(‘222‘) 47 } 48 componentWillUnmount() { 49 this.clearInterval(); 50 } 51 render(){ 52 // console.log(TimerMixin) 53 // console.log(this.props.isSend) 54 let {count,counting} = this.state; 55 return( 56 <Button 57 disabled={counting} 58 className="verificationCode" 59 onClick={this.phone} 60 >{ 61 counting? `${count}秒后重发` :‘获取验证码‘ 62 }</Button> 63 ) 64 65 } 66 } 67 SendVerifyCode.propTypes = { 68 isSend: PropTypes.bool.isRequired, 69 onhandlePhone: PropTypes.func.isRequired, 70 onSuccessSend: PropTypes.func.isRequired 71 } 72 73 SendVerifyCode.defaultProps = { 74 isSend: false 75 } 76 export default SendVerifyCode;
原文地址:https://www.cnblogs.com/dglblog/p/9473669.html
时间: 2024-10-20 16:38:02