pro-components icon indicating copy to clipboard operation
pro-components copied to clipboard

👑 [需求] 能否提供一个,验证码输入控件

Open leshalv opened this issue 2 years ago • 2 comments

image

leshalv avatar Aug 04 '22 00:08 leshalv

这个是pc端的 pro components,可以给ant design mobile pro compoents 提个issue

liangchaofei avatar Aug 04 '22 03:08 liangchaofei

这个是pc端的 pro components,可以给ant design mobile pro compoents 提个issue

这个也是pc端的需求

leshalv avatar Aug 04 '22 03:08 leshalv

TAutomatically replying with ChatGPT can be attempted, but it cannot be guaranteed to be completely accurate and may not fully address all issues. Please feel free to reply if you have any further questions or concerns. 此回复基于 ChatGPT 自动生成,可以尝试下方案,官方员会在一定时间后继续继续处理。

好的,针对您提出的需求,可以使用 Ant Design 的 InputButton 组件配合使用实现验证码输入控件。

主要思路如下:

  1. Input 中输入手机号,并在点击发送验证码按钮后发请求向后端发送请求,获取验证码。为了更好的用户体验,我们可以加上一些点击按钮之后的加载效果。
  2. Input 的右侧添加一个 Button 组件,用来发送验证码,我们可以借助到 Countdown 组件实现倒计时效果。
  3. 点击发送验证码之后,Button 组件倒计时,同时处于倒计时状态时,要禁止用户重复点击。

具体的实现代码如下:

import React, { useState, useEffect } from "react";
import { Input, Button, message } from "antd";
import { SendOutlined } from "@ant-design/icons";
import Countdown from "antd/lib/statistic/Countdown";

const VerifyCodeInput = () => {
  const [phone, setPhone] = useState(""); // 手机号
  const [countdown, setCountdown] = useState(0); // 倒计时时间
  const [isDisabled, setIsDisabled] = useState(false); // 发送验证码按钮是否不可用

  // 点击发送验证码按钮后的事件处理函数
  const handleSendVerifyCode = () => {
    setIsDisabled(true); // 发送验证码按钮设置为不可用
    // 此处应发送Ajax请求获取验证码
    message.success("验证码已发送,请注意查收!");
    setCountdown(60); // 开始倒计时
  };

  useEffect(() => {
    let timer = null;
    if (countdown > 0) { // 正在倒计时
      timer = setTimeout(() => {
        setCountdown(prevCountdown => prevCountdown - 1);
      }, 1000);
    } else { // 倒计时结束
      setIsDisabled(false); // 发送验证码按钮设置为可用
    }
    return () => {
      clearTimeout(timer); // 组件卸载时,清除计时器
    };
  }, [countdown]);

  return (
    <>
      <Input
        addonBefore="+86"
        value={phone}
        onChange={e => setPhone(e.target.value)}
        style={{ width: 200 }}
        placeholder="请输入手机号码"
      />
      <Button
        style={{ marginLeft: "16px" }}
        type="primary"
        icon={<SendOutlined />}
        disabled={!phone || isDisabled}
        onClick={handleSendVerifyCode}
      >
        发送验证码
      </Button>
      {countdown > 0 && (
        <span style={{ marginLeft: "16px" }}>
          <Countdown value={Date.now() + countdown * 1000} format="ss秒" />
        </span>
      )}
    </>
  );
};

export default VerifyCodeInput;

在这段代码中,我们引入了 Ant Design 的 InputButtonCountdown 组件,其中:

  • Input 组件使用了 addonBefore 属性设定了前缀 +86,方便用户识别输入的是手机号,valueonChange 属性分别用来获取和设置输入框中的手机号码。
  • Button 组件使用了 type 属性设置按钮类型为主要按钮,icon 属性指定了发送图标,disabled 属性在手机号码为空或正在倒计时时禁用按钮,onClick 属性绑定了发送验证码事件处理函数。
  • Countdown 组件用来显示倒计时时间,value 属性指定了倒计时结束的时间,format 属性指定了倒计时时间的格式。

chenshuai2144 avatar Mar 06 '23 10:03 chenshuai2144