利用React-Native怎么實現(xiàn)一個驗證碼倒計時按鈕?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
在承留等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供成都網(wǎng)站建設、做網(wǎng)站 網(wǎng)站設計制作按需設計,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,高端網(wǎng)站設計,成都全網(wǎng)營銷推廣,成都外貿(mào)網(wǎng)站制作,承留網(wǎng)站建設費用合理。開發(fā)過程中有獲取手機驗證碼的場景,這時候有這樣的要求:
1,點擊“獲取驗證碼”的按鈕,發(fā)起獲取驗證碼的網(wǎng)絡請求,同時按鈕置為不可用
2,如果網(wǎng)絡請求成功,按鈕繼續(xù)不可用,但按鈕上文本改為倒計時((*s)后重新獲取)
3,如果網(wǎng)絡請求失敗,按鈕置為可用
4,倒計時結束,按鈕可用
源碼:
import React,{PropTypes} from 'react'; import {View,Text,TouchableOpacity} from 'react-native'; export default class TimerButton extends React.Component { constructor(props) { super(props) this.state = { timerCount: this.props.timerCount || 90, timerTitle: this.props.timerTitle || '獲取驗證碼', counting: false, selfEnable: true, }; this._shouldStartCountting = this._shouldStartCountting.bind(this) this._countDownAction = this._countDownAction.bind(this) } static propTypes = { style: PropTypes.object, textStyle: Text.propTypes.style, onClick: PropTypes.func, disableColor: PropTypes.string, timerTitle: PropTypes.string, enable: React.PropTypes.oneOfType([React.PropTypes.bool,React.PropTypes.number]) }; _countDownAction(){ const codeTime = this.state.timerCount; this.interval = setInterval(() =>{ const timer = this.state.timerCount - 1 if(timer===0){ this.interval&&clearInterval(this.interval); this.setState({ timerCount: codeTime, timerTitle: this.props.timerTitle || '獲取驗證碼', counting: false, selfEnable: true }) }else{ console.log("---- timer ",timer); this.setState({ timerCount:timer, timerTitle: `重新獲取(${timer}s)`, }) } },1000) } _shouldStartCountting(shouldStart){ if (this.state.counting) {return} if (shouldStart) { this._countDownAction() this.setState({counting: true,selfEnable:false}) }else{ this.setState({selfEnable:true}) } } componentWillUnmount(){ clearInterval(this.interval) } render(){ const {onClick,style,textStyle,enable,disableColor} = this.props const {counting,timerTitle,selfEnable} = this.state return ({ if (!counting && enable && selfEnable) { this.setState({selfEnable:false}) this.props.onClick(this._shouldStartCountting) }; }}> ) } }{timerTitle}