在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登录的资料请关注编程宝库其它相关文章!

微信小程序组件设计规范组件化开发的思想贯穿着我开发设计过程的始终。在过去很长一段时间里,我都受益于这种思想。 组件可复用 - 减少了重复代码量 组件做为抽离的功能单元 - 方便维护 组件作为templat ...