详解对于React结合Antd的Form组件实现登录功能

一、React 结合 Antd 实现登录功能

引入所需的 Antd 组件,代码如下所示:

import { Form, Icon, Input, Button, message } from 'antd'

在 Login.jsx 中,创建一个 Login 组件。当对外暴露组件时,需要使用 Form 组件进行包装,包装 Form 组件生成一个新的组件 Form(Login),同时新组件会向 Form 组件传递一个强大的对象属性 form,这样就可以取到 Form 表单的值,这也是高阶组件和高阶函数的体现,代码如下所示:

class Login extends Component {} const WrapLogin = Form.create()(Login) export default WrapLogin

在 render 内部去渲染表单时,可以先通过 this.props 去拿到 form 表单,在 form 中取得 getFieldDecorator,用于和表单进行双向绑定。在 getFieldDecorator 中,第一项是表单项对应的 value 值,第二项是配置对象,属性名是特定的一些名称。比如,rules 是验证规则,在 rules 中,可以设置 required 为是否必选,message 为校验文案,pattern 为正则表达式校验,max 为最大长度,min 为最小长度。还比如 initialValue 是表单项的初始值。对于 rules 校验,可以使用声明式验证, 也就是直接使用别人定义好的验证规则进行验证,还可以自定义验证 validator,function(rule, value, callback),必须有 callback 回调函数,代码如下所示:

class Login extends Component { validPwd = (rule, value, callback) => { if (!value) { callback('密码必须输入') } else if (value.length < 4) { callback('密码长度不能小于4位') } else if (value.length > 12) { callback('密码长度不能大于12位') } else if (!/^[a-zA-Z0-9_]+$/.test(value)) { callback('密码必须是英文、数字或下划线组成') } else { callback() } } render () { const form = this.props.form const { getFieldDecorator } = form return ( <div className="login"> <header className="login-header"> <img src=https://www.jb51.net/article/{logo} alt="logo"></img> <h1>React 后台管理系统</h1> </header> <section className="login-content"> <h2>用户登录</h2> <Form> <Form.Item> { getFieldDecorator('username', { rules: [ { required: true, whitespace: true, message: '用户名必须输入'}, { min: 4, message: '用户名至少是4位'}, { max: 12, message: '用户名至少是12位'}, { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文、数字或下划线组成'} ], // initialValue: 'admin', })( <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" /> ) } </Form.Item> <Form.Item> { getFieldDecorator('password', { rules: [ { validator: this.validPwd } ] })( <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" /> ) } </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className="login-form-button"> 登陆 </Button> </Form.Item> </Form> </section> </div> ) } } const WrapLogin = Form.create()(Login) export default WrapLogin

我们可以定义两个工具类,用来操作登录对象,memoryUtils 是用来在内存保存一些数据的工具模块,storageUtils 是进行 local 数据存储管理的工具模块,如下所示:

memoryUtils.js,代码如下所示:

export default { user: {}, product: {} }

storageUtils.js,代码如下所示:

import store from 'store' const USER_KEY = 'user_key' export default { // 保存 user saveUser (user) { store.set(USER_KEY, user) }, // 读取 user getUser () { return store.get(USER_KEY) || {} }, // 删除 user removeUser () { store.remove(USER_KEY) } }

定义登录的接口请求函数,使用 axios 可以先进行封装,得到 response.data,如下所示:

ajax.js,代码如下所示:

import axios from 'axios' import {message} from 'antd' export default function ajax(url, data={}, type='GET') { return new Promise((resolve, reject) => { let promise if(type==='GET') { promise = axios.get(url, { params: data }) } else { promise = axios.post(url, data) } promise.then(response => { resolve(response.data) }).catch(error => { message.error('请求出错了: ' + error.message) }) }) }

index.js,代码如下所示:

import jsonp from 'jsonp' import ajax from './ajax' import { message } from 'antd' const BASE = '' export const reqLogin = (username, password) => ajax(BASE + '/login', { username, password}, 'POST') export const reqCategories = (parentId) => ajax(BASE + '/manage/category/list', {parentId}) export const reqAddCategories = ({parentId, categoryName}) => ajax(BASE + '/manage/category/add', {parentId, categoryName}, 'POST') export const reqUpdateCategories = ({categoryId, categoryName}) => ajax(BASE + '/manage/category/update', {categoryId, categoryName}, 'POST') export const reqCategory = (categoryId) => ajax(BASE + '/manage/category/info', { categoryId }) export const reqProducts = ({pageNum, pageSize}) => ajax(BASE + '/manage/product/list', { pageNum, pageSize}) export const reqUpdateStatus = ({productId, status}) => ajax(BASE + '/manage/product/updateStatus', {productId, status}, 'POST') export const reqSearchProducts = ({ pageNum, pageSize, searchName, searchType}) => ajax(BASE + '/manage/product/search', { pageNum, pageSize, [searchType]: searchName }) export const reqDeleteImg = (name) => ajax(BASE + '/manage/img/delete', {name}, 'POST') export const reqAddUpdateProduct = (product) => ajax(BASE + '/manage/product/' + (product._id ? 'update' : 'add'), product, 'POST') export const reqRoles = () => ajax(BASE + '/manage/role/list') export const reqAddRole = (roleName) => ajax(BASE + '/manage/role/add', {roleName}, 'POST') export const reqUpdateRole = (role) => ajax(BASE + '/manage/role/update', role, 'POST') export const reqUsers = () => ajax(BASE + '/manage/user/list') export const reqDeleteUser = (userId) => ajax(BASE + '/manage/user/delete', {userId}, 'POST') export const reqAddOrUpdateUser = (user) => ajax(BASE + '/manage/user/'+(user._id ? 'update': 'add'), user, 'POST') export const reqWeather = (city) => { return new Promise((resolve, reject) => { const url = `?location=${city}&output=json&ak=IOXimfoqOUVq2KcYCiQU9cMF7hyN5kFB` jsonp(url, {}, (err, data) => { console.log('jsonp()', err, data) if (!err && data.status==='success') { const {dayPictureUrl, weather} = data.results[0].weather_data[0] resolve({dayPictureUrl, weather}) } else { message.error('获取天气信息失败!') } }) }) }

引入这些工具类和接口,代码如下所示:

import { reqLogin } from '../../api' import memoryUtils from '../../utils/memoryUtils' import storageUtils from '../../utils/storageUtils'

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsdgfw.html