React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > Ant Design Pro登录

在Ant Design Pro登录功能中集成图形验证码组件的方法步骤

作者:hanxiaozhang2018

这篇文章主要介绍了在Ant Design Pro登录功能中集成图形验证码组件的方法步骤,这里的登录功能其实就是一个表单提交,实现起来也很简单,具体实例代码跟随小编一起看看吧

前言:

本篇文章只介绍在Ant Design Pro登录功能中集成图形验证码组件的方法步骤,服务端方法请参考《基于OAuth2.0授权系统的验证码功能》

正文:

在Ant Design Pro模板中,使用账号密码登录功能部分(如下图),并没有做图形验证码的开发,所以这部分功能就需要我们自己去实现。这里登录功能其实本质是一个表单提交,所以我们只需自己开发一个图形验证码表单控件就可以,具体实现如下。

1. 图形验证码表单控件代码CaptchaInput.tsx:

import React, {useState, useEffect} from 'react';
import {Input, message} from 'antd';
import {SafetyCertificateOutlined} from '@ant-design/icons';
import api from '@/utils/api';
import stringUtil from "@/utils/stringUtil";
import request from "@/utils/request";
import {useIntl} from "umi";
 
 
interface CaptchaInputValue {
  captchaCode?: string;
  captchaKey?: string;
}
 
interface CaptchaInputProps {
  value?: CaptchaInputValue;
  onChange?: (value: CaptchaInputValue) => void;
}
 
/**
 * 获取验证码
 */
const getCaptcha = async () => {
  try {
    const data = await request(api.captcha);
    if (data.code === 1) {
      return data.data;
    }
  } catch (error) {
    message.error('获取部门树失败,请重试');
    return [];
  }
  message.error('获取部门树失败,请重试');
  return [];
}
 
const CaptchaInput: React.FC<CaptchaInputProps> = ({value = {}, onChange}) => {
 
  const intl = useIntl();
  const [captchaCode, setCaptchaCode] = useState<string>('');
  const [captchaKey, setCaptchaKey] = useState<string>('');
  const [imageData, setImageData] = useState<string>('');
 
  // 触发改变
  const triggerChange = (changedValue: { captchaCode?: string; captchaKey?: string }) => {
    if (onChange) {
      onChange({captchaCode, captchaKey, ...value, ...changedValue});
    }
  };
 
  useEffect(() => {
    getCaptcha().then((data: any) => {
      setCaptchaKey(data.captchaKey);
      setImageData(data.image);
      triggerChange({captchaKey: data.captchaKey});
    })
  }, []);
 
 
  // 输入框变化
  const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const code = e.target.value || '';
    if (stringUtil.isNotEmpty(code)) {
      setCaptchaCode(code);
    }
    triggerChange({captchaCode: code});
  }
 
  // 时间类型变化
  const onClickImage = () => {
    getCaptcha().then((data: any) => {
      setCaptchaKey(data.captchaKey);
      setImageData(data.image);
      triggerChange({captchaKey: data.captchaKey});
    })
  };
 
  return (
    <span>
       <Input.Group compact>
          <Input prefix={<SafetyCertificateOutlined style={{color: "#319cff"}}/>} placeholder={intl.formatMessage({
            id: 'pages.login.captcha.placeholder',
            defaultMessage: '请输入验证码',
          })}
                 onChange={onChangeInput}
                 style={{width: '75%', marginRight: 5, padding: '6.5px 11px 6.5px 11px', verticalAlign: 'middle'}}/>
                   <img style={{width: '23%', height: '35px', verticalAlign: 'middle', padding: '0px 0px 0px 0px'}}
                        src={imageData} onClick={onClickImage}/>
       </Input.Group>
    </span>
  );
};
export default CaptchaInput;

2.登录页面集成组件:

import CaptchaInput from './components/CaptchaInput';
 
...   ... 
 
  const handleSubmit = (values: LoginParamsType) => {
    const {dispatch} = props;
    values.client_id = "hanxiaozhang";
    values.client_secret = "hanxiaozhang";
    values.scope = "hanxiaozhang";
    values.grant_type = "password";
    values.captcha_key = values.captchaComp.captchaKey;
    values.captcha_code = values.captchaComp.captchaCode;
    delete values.captchaComp;
    dispatch({
      type: 'login/login',
      payload: {...values, type},
    });
  };
 
...   ... 
 
            <Form.Item name="captchaComp" rules={[{
              validateTrigger: 'onBlur',
              validator: async (rule, value) => {
                // console.log(rule)
                if (stringUtil.isEmpty(value.captchaCode)) {
                  throw new Error('请输入验证码!');
                }
              }
            },]}>
              <CaptchaInput/>
            </Form.Item>
 
...   ...

 3.使用:

集成之后的效果如下:

以上就是在Ant Design Pro登录功能中集成图形验证码组件的详细内容,更多关于Ant Design Pro登录的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文