手机发送验证码(简易版):

75 阅读1分钟

import React, { useState } from 'react';

import './SendCode.scss';

import { Input, Button } from 'antd-mobile'

export default function SendCode(props) {

    const setSendCode = () => {

        // console.log('子组件触发了');

        const mobile = props.mobile;

        // 手机号验证函数  返回true/false

        const regex = /^1[3-9]\d{9}$/

        let isRegex = regex.test(mobile)

        let state = '';

        let msg = '';

        let code = '';

        if (isRegex) { //手机号满足验证条件时

            //

            let codedom = document.querySelector('.codes')

            let timer = ''

            clearInterval(timer)

            let time = 10;

            timer = setInterval(() => {

                console.log('定时器');

                if (time > 0) {

                    time--;

                    codedom.innerHTML = 倒计时 (${time})

                    // console.log(time, 'time');

                } else {

                    // console.log('定时器关闭了');

                    codedom.innerHTML = '发送验证码'

                }

            }, 1000)

            state = 200;

            msg = '手机号验证成功';

            code = Math.floor(Math.random() * 10).toString() + Math.floor(Math.random() * 10).toString() + Math.floor(Math.random() * 10).toString() + Math.floor(Math.random() * 10).toString()

        } else { //手机号不满足时

            state = 201;

            msg = '手机号为空/或手机号不存在';

            code = ''

        }

        props.clickCode({ 'state': state, 'msg': msg, 'code': code })

    }

    return (

        <Button className='codes' onClick={() => { setSendCode() }} >发送验证码

    )

}