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 } = res
              if (+resultCode === 0) {
                  setSafePhoneInfo({ ...safePhoneInfo, uniqueId: data })
              }
          })
          // 这里写一个定时器就可以去更新灰色按钮的内容而且show_btn是false时会出现灰色按钮,当倒计时结束又变成可以触发的按钮
          timer = setInterval(() => {
              setCountDownInfo((pre) => {
                  if (pre.count === 1) {
                      clearInterval(timer)
                      pre.count = 60
                      pre.show_btn = true
                      pre.code_ts = '获取验证码'
                  } else {
                      pre.count = count--
                      pre.show_btn = false
                      pre.code_ts = count + 's'
                  }
                  return pre
              })
          }, 1000)
      }
  }
  const formChange = (key, value) => {
      safePhoneInfo[key] = value
      setSafePhoneInfo({ ...safePhoneInfo })
  }
return (
    
        {originalData.phone && (
            
                
            
        )}
        
             {
                    formChange('cardCode', e)
                }}
                />
             {
                    formChange('phone', e)
                }}
                />
             {
                    formChange('mobileCode', e)
                }}
                >
                {countDownInfo.show_btn ? (
                     getCode()}
                        >
                        获取验证码
                    
                ) : (
                    
                        {countDownInfo.code_ts}
                    
                )}
            
        
    
)

你可能感兴趣的:(笔记,typescript,javascript,开发语言)