前言
在日常的开发中,我们可能经常会做获取验证码的功能,市场上也有很多已经封装好的第三方组件,但很多时候需要我们二开。下面是基于Ant Design组件来进行二开的
一、官方组件
源码如下:
<ProFormCaptcha
fieldProps={{
size: 'large',
prefix: <LockOutlined className={'prefixIcon'} />,
}}
captchaProps={{
size: 'large',
}}
placeholder={'请输入验证码'}
captchaTextRender={(timing, count) => {
if (timing) {
return `${count} ${'获取验证码'}`;
}
return '获取验证码';
}}
name="captcha"
rules={[
{
required: true,
message: '请输入验证码!',
},
]}
onGetCaptcha={async () => {
message.success('获取验证码成功!验证码为:1234');
}}
/>
这是ProComponents登录组件中所使用的获取手机验证码的,有一个60秒倒计时,可符合日常简单的开发使用。
二、基于官方组件二次开发
先将倒计时功能封装为单独的ts文件
import { useEffect, useRef, useState } from 'react';
/** 验证码倒计时 */
export function useCaptchaTimer() {
const [second, setSecond] = useState(60);
const [btnDisabled, setBtnDisabled] = useState(true);
const timerRef = useRef<any>(null);
useEffect(() => {
return () => clearInterval(timerRef.current);
}, []);
useEffect(() => {
if (second > 0 && second < 60) {
// 定时器超时
} else {
clearInterval(timerRef.current);
setBtnDisabled(false);
setSecond(60);
}
}, [second]);
// 开始倒计时
const startCountdown = () => {
clearInterval(timerRef.current);
timerRef.current = setInterval(() => setSecond(prevSecond => prevSecond - 1), 1000);
setBtnDisabled(true);
};
// 停止倒计时
const stopCountdown = () => {
clearInterval(timerRef.current);
setBtnDisabled(false);
setSecond(60);
};
return { second, btnDisabled, startCountdown, stopCountdown };
}
然后,在需要使用的组件中导入即可使用
<ProFormText
label='验证码'
name='code'
fieldProps={{
size: 'large',
prefix: <LockOutlined />,
}}
placeholder='请输入验证码!'
rules={[
{
required: true,
message: '请输入验证码!',
},
]}
/>
<Button
className='mt-1.5'
size='large'
disabled={btnDisabled}
onClick={getCaptcha}
loading={loading}
>
{!btnDisabled ? '获取验证码' : `${second}s 后重新获取`}
</Button>
在这里,可配合输入框来进行动态的获取,当输入框为空时,获取验证码按钮为禁用状态。