本文主要是介绍Taro Hooks 实现手机短信验证码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Taro Hooks 实现手机短信验证码
const [safePhoneInfo, setSafePhoneInfo] = useState({})
const [originalData, setOriginalData] = useState({})
const [countDownInfo, setCountDownInfo] = useState({icode: '',code_ts: '获取验证码',show_btn: true,toast: false,count: 60,uniqueId: '',
})const getCode = () => {if (safePhoneInfo.phone === '' ||!/^1[3456789]\d{9}$/.test(safePhoneInfo.phone)) {// 这里验证一下号码格式是否正确,为空或者不正常都提示一下,然后激活提示控件true,其他的框架提示控件同理Taro.showToast({title: '请输入正确手机号',icon: 'none',duration: 1000,mask: true, // 防止触摸穿透})} else {let count = countDownInfo.count//发起短信接口Request({url: '/v2/code',method: 'POST',data: {type: '1',target: safePhoneInfo.phone,},}).then((res) => {const { resultCode, data } = resif (+resultCode === 0) {setSafePhoneInfo({ ...safePhoneInfo, uniqueId: data })}})// 这里写一个定时器就可以去更新灰色按钮的内容而且show_btn是false时会出现灰色按钮,当倒计时结束又变成可以触发的按钮timer = setInterval(() => {setCountDownInfo((pre) => {if (pre.count === 1) {clearInterval(timer)pre.count = 60pre.show_btn = truepre.code_ts = '获取验证码'} else {pre.count = count--pre.show_btn = falsepre.code_ts = count + 's'}return pre})}, 1000)}}const formChange = (key, value) => {safePhoneInfo[key] = valuesetSafePhoneInfo({ ...safePhoneInfo })}
return (<View className="">{originalData.phone && (<AtForm className="form"><AtListItemclassName="form-required"title="原手机号"extraText={originalData.phone}arrow=""/></AtForm>)}<AtForm className="form"><AtInput// requiredtype="text"placeholder="请填写身份证号"value={safePhoneInfo.cardCode}onChange={(e) => {formChange('cardCode', e)}}/><AtInput// requiredtype="text"placeholder="请填写手机"value={safePhoneInfo.phone}onChange={(e) => {formChange('phone', e)}}/><AtInput// required// title=" 短信验证码"type="number"placeholder="请填写短信验证码"value={safePhoneInfo.mobileCode}onChange={(e) => {formChange('mobileCode', e)}}>{countDownInfo.show_btn ? (<AtButtonclassName="get-code"size="small"type="secondary"onClick={() => getCode()}>获取验证码</AtButton>) : (<View className="count-zero">{countDownInfo.code_ts}</View>)}</AtInput></AtForm></View>
)
这篇关于Taro Hooks 实现手机短信验证码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!