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 (
<View className="">
{originalData.phone && (
<AtForm className="form">
<AtListItem
className="form-required"
title="原手机号"
extraText={originalData.phone}
arrow=""
/>
</AtForm>
)}
<AtForm className="form">
<AtInput
// required
type="text"
placeholder="请填写身份证号"
value={safePhoneInfo.cardCode}
onChange={(e) => {
formChange('cardCode', e)
}}
/>
<AtInput
// required
type="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 ? (
<AtButton
className="get-code"
size="small"
type="secondary"
onClick={() => getCode()}
>
获取验证码
</AtButton>
) : (
<View className="count-zero">
{countDownInfo.code_ts}
</View>
)}
</AtInput>
</AtForm>
</View>
)