React中發送驗證碼 倒計時效果組件編寫
阿新 • • 發佈:2018-08-14
stat ear hand disabled 信息 led con 判斷 自動
(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;
React中發送驗證碼 倒計時效果組件編寫