1. 程式人生 > 其它 >React-hooks/TypeScript/Taro 實現傳送驗證碼倒計時

React-hooks/TypeScript/Taro 實現傳送驗證碼倒計時

import { Form, Toast, Cell, Input, Field, Button } from '@taroify/core';
import { View } from '@tarojs/components';
import React, { useEffect, useState } from 'react';

import styles from './index.module.scss';
let timeFun: NodeJS.Timer;

const UsernameLogin: React.FC = () => {
  const [btnTitle, setBtnTitle] 
= useState<string>('傳送驗證碼'); const [btnDisabled, setBtnDisabled] = useState<boolean>(false); const [time, setTime] = useState<number>(60); useEffect(() => { clearInterval(timeFun); return () => { clearInterval(timeFun); }; }, []); useEffect(() => {
if (btnDisabled && time > 0 && time < 60) { setBtnTitle(`${time}s後重發`); } else { setBtnTitle('傳送驗證碼'); setBtnDisabled(false); setTime(60); clearInterval(timeFun); } }, [time]); const onSubmit = () => {}; const sendVerifCode = () => {
// eslint-disable-next-line timeFun = setInterval(() => setTime((t) => --t), 1000); setBtnDisabled(true); }; return ( <View className={styles.page}> <Form onSubmit={onSubmit}> <Toast id='toast' /> <Cell.Group inset> <Field label={{ align: 'left', children: '驗證碼' }} name='text' rules={[{ required: true, message: '請填寫驗證碼' }]} > <Input placeholder='請輸入驗證碼' /> <Button color='primary' disabled={btnDisabled} onClick={sendVerifCode} size='small'> {btnTitle} </Button></Field> </Cell.Group> <View style={{ margin: '16px' }}> <Button block color='primary' formType='submit' shape='round' style={{ backgroundColor: '#1aad19', color: '#fff' }} > 登入 </Button> </View> </Form> </View> ); }; export default UsernameLogin;