国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務器之家 - 編程語言 - JavaScript - React - 詳解對于React結合Antd的Form組件實現登錄功能

詳解對于React結合Antd的Form組件實現登錄功能

2022-02-23 16:31浮生離夢 React

這篇文章主要介紹了詳解對于React結合Antd的Form組件實現登錄功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

 

一、React 結合 Antd 實現登錄功能

引入所需的 Antd 組件,代碼如下所示:

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

在 Login.jsx 中,創建一個 Login 組件。當對外暴露組件時,需要使用 Form 組件進行包裝,包裝 Form 組件生成一個新的組件 Form(Login),同時新組件會向 Form 組件傳遞一個強大的對象屬性 form,這樣就可以取到 Form 表單的值,這也是高階組件和高階函數的體現,代碼如下所示:

?
1
2
3
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 回調函數,代碼如下所示:

  1. class Login extends Component { 
  2.  validPwd = (rule, value, callback) => { 
  3.   if (!value) { 
  4.    callback('密碼必須輸入'
  5.   } else if (value.length < 4) { 
  6.    callback('密碼長度不能小于4位'
  7.   } else if (value.length > 12) { 
  8.    callback('密碼長度不能大于12位'
  9.   } else if (!/^[a-zA-Z0-9_]+$/.test(value)) { 
  10.    callback('密碼必須是英文、數字或下劃線組成'
  11.   } else { 
  12.    callback() 
  13.   } 
  14.  } 
  15.  
  16.  render () { 
  17.   const form = this.props.form 
  18.   const { getFieldDecorator } = form 
  19.  
  20.   return ( 
  21.    <div className="login"
  22.     <header className="login-header"
  23.      <img src={logo} alt="logo"></img> 
  24.      <h1>React 后臺管理系統</h1> 
  25.     </header> 
  26.     <section className="login-content"
  27.      <h2>用戶登錄</h2> 
  28.      <Form> 
  29.       <Form.Item> 
  30.        { 
  31.         getFieldDecorator('username', { 
  32.          rules: [ 
  33.           { required: true, whitespace: true, message: '用戶名必須輸入'}, 
  34.           { min: 4, message: '用戶名至少是4位'}, 
  35.           { max: 12, message: '用戶名至少是12位'}, 
  36.           { pattern: /^[a-zA-Z0-9_]+$/, message: '用戶名必須是英文、數字或下劃線組成'
  37.          ], 
  38.          // initialValue: 'admin', 
  39.         })( 
  40.          <Input 
  41.           prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} 
  42.           placeholder="用戶名" 
  43.          /> 
  44.         ) 
  45.        } 
  46.       </Form.Item> 
  47.       <Form.Item> 
  48.        { 
  49.         getFieldDecorator('password', { 
  50.          rules: [ 
  51.           { validator: this.validPwd } 
  52.          ] 
  53.         })( 
  54.          <Input 
  55.           prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} 
  56.           type="password" 
  57.           placeholder="密碼" 
  58.          /> 
  59.         ) 
  60.        } 
  61.       </Form.Item> 
  62.       <Form.Item> 
  63.        <Button type="primary" htmlType="submit" className="login-form-button"
  64.          登陸 
  65.        </Button> 
  66.       </Form.Item> 
  67.      </Form> 
  68.     </section> 
  69.    </div> 
  70.   ) 
  71.  } 
  72.  
  73. const WrapLogin = Form.create()(Login) 
  74. export default WrapLogin 

我們可以定義兩個工具類,用來操作登錄對象,memoryUtils 是用來在內存保存一些數據的工具模塊,storageUtils 是進行 local 數據存儲管理的工具模塊,如下所示:

memoryUtils.js,代碼如下所示:

?
1
2
3
4
export default {
 user: {},
 product: {}
}

storageUtils.js,代碼如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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,代碼如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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,代碼如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 = `http://api.map.baidu.com/telematics/v3/weather?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('獲取天氣信息失敗!')
   }
 
  })
 })
}

引入這些工具類和接口,代碼如下所示:

?
1
2
3
import { reqLogin } from '../../api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'

給 Form 表單綁定 onSubmit 事件,handleSubmit。在這個事件中,需要先使用 event.preventDefault() 阻止事件的默認行為。如果想要獲取表單項的輸入數據,可以使用 form.getFieldsValue()。但是,在提交表單前需要對表單數據進行預校驗,使用 this.props.form.validateFields 進行預校驗,validateFields 可以獲取所有表單字段的值,并且可以判斷表單數據是否有錯。如有 沒錯,說明預校驗通過,從 values 中獲取 username 和 password 的值,然后通過 reqLogin 這個接口結合 async 和 await 發起登錄請求。如果響應的狀態碼正確,說明登錄成功,保存 user,保存在內存和本地中,然后使用 this.props.history.replace 跳轉到主管理界面中,反之則登錄失敗。在 render 中,如果用戶已經登陸, 需要使用 Redirect 自動跳轉到主管理界面中,代碼如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
handleSubmit = (event) => {
 event.preventDefault()
 
 this.props.form.validateFields(async (err, values) => {
  if (!err) {
   const { username, password } = values
   const result = await reqLogin(username, password)
   if (result.status === 0) {
    message.success('登錄成功')
    const user = result.data
    memoryUtils.user = user
    storageUtils.saveUser(user)
    this.props.history.replace('/')
   } else {
    message.error(result.msg)
   }
  } else {
   console.log(err)
  }
 })

 

二、React 結合 Antd 實現登錄功能的實現

React 結合 Antd 實現登錄功能的實現,完整代碼如下所示:
login.jsx,代碼如下所示:

  1. import React, { Component } from 'react' 
  2. import { Form, Icon, Input, Button, message } from 'antd' 
  3. import { Redirect } from 'react-router-dom' 
  4. import './login.less' 
  5. import logo from '../../assets/images/logo.png' 
  6. import { reqLogin } from '../../api' 
  7. import memoryUtils from '../../utils/memoryUtils' 
  8. import storageUtils from '../../utils/storageUtils' 
  9.  
  10. class Login extends Component { 
  11.  
  12.  handleSubmit = (event) => { 
  13.   event.preventDefault() 
  14.  
  15.   this.props.form.validateFields(async (err, values) => { 
  16.    if (!err) { 
  17.     const { username, password } = values 
  18.     const result = await reqLogin(username, password) 
  19.     if (result.status === 0) { 
  20.      message.success('登錄成功'
  21.      const user = result.data 
  22.      memoryUtils.user = user 
  23.      storageUtils.saveUser(user) 
  24.  
  25.      this.props.history.replace('/'
  26.     } else { 
  27.      message.error(result.msg) 
  28.     } 
  29.    } else { 
  30.     console.log(err) 
  31.    } 
  32.   }) 
  33.  
  34.  } 
  35.  
  36.  validPwd = (rule, value, callback) => { 
  37.   if (!value) { 
  38.    callback('密碼必須輸入'
  39.   } else if (value.length < 4) { 
  40.    callback('密碼長度不能小于4位'
  41.   } else if (value.length > 12) { 
  42.    callback('密碼長度不能大于12位'
  43.   } else if (!/^[a-zA-Z0-9_]+$/.test(value)) { 
  44.    callback('密碼必須是英文、數字或下劃線組成'
  45.   } else { 
  46.    callback() 
  47.   } 
  48.  } 
  49.  
  50.  
  51.  render () { 
  52.  
  53.   const user = memoryUtils.user 
  54.   if (user && user._id) { 
  55.    return <Redirect to="/"></Redirect> 
  56.   } 
  57.  
  58.   const form = this.props.form 
  59.   const { getFieldDecorator } = form 
  60.  
  61.   return ( 
  62.    <div className="login"
  63.     <header className="login-header"
  64.      <img src={logo} alt="logo"></img> 
  65.      <h1>React 后臺管理系統</h1> 
  66.     </header> 
  67.     <section className="login-content"
  68.      <h2>用戶登錄</h2> 
  69.      <Form onSubmit={this.handleSubmit}> 
  70.       <Form.Item> 
  71.        { 
  72.         getFieldDecorator('username', { 
  73.          rules: [ 
  74.           { required: true, whitespace: true, message: '用戶名必須輸入'}, 
  75.           { min: 4, message: '用戶名至少是4位'}, 
  76.           { max: 12, message: '用戶名至少是12位'}, 
  77.           { pattern: /^[a-zA-Z0-9_]+$/, message: '用戶名必須是英文、數字或下劃線組成'
  78.          ], 
  79.          // initialValue: 'admin', 
  80.         })( 
  81.          <Input 
  82.           prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} 
  83.           placeholder="用戶名" 
  84.          /> 
  85.         ) 
  86.        } 
  87.       </Form.Item> 
  88.       <Form.Item> 
  89.        { 
  90.         getFieldDecorator('password', { 
  91.          rules: [ 
  92.           { validator: this.validPwd } 
  93.          ] 
  94.         })( 
  95.          <Input 
  96.           prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} 
  97.           type="password" 
  98.           placeholder="密碼" 
  99.          /> 
  100.         ) 
  101.        } 
  102.       </Form.Item> 
  103.       <Form.Item> 
  104.        <Button type="primary" htmlType="submit" className="login-form-button"
  105.          登陸 
  106.        </Button> 
  107.       </Form.Item> 
  108.      </Form> 
  109.     </section> 
  110.    </div> 
  111.   ) 
  112.  } 
  113.  
  114. const WrapLogin = Form.create()(Login) 
  115. export default WrapLogin 

login.less,代碼如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
.login {
 width: 100%;
 height: 100%;
 background-image: url('./images/bg.jpg');
 background-size: 100% 100%;
 .login-header {
  display: flex;
  align-items: center;
  height: 80px;
  background-color: rgba(21, 20, 13, 0.5);
  img {
   width: 40px;
   height: 40px;
   margin: 0 15px 0 50px;
  }
  h1 {
   font-size: 30px;
   color: white;
  }
 }
 
 .login-content {
  width: 400px;
  height: 300px;
  background-color: #fff;
  margin: 50px auto;
  padding: 20px 40px;
  h2 {
   text-align: center;
   font-size: 30px;
   font-weight:bold;
   margin-bottom: 20px;
  }
  .login-form {
   .login-form-button {
    width: 100%;
   }
  }
 }
}

到此這篇關于詳解對于React結合Antd的Form組件實現登錄功能的文章就介紹到這了,更多相關React Antd Form登錄內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/weixin_42614080/article/details/115043019

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 久久久国产一区二区三区 | 欧美一区永久视频免费观看 | 日韩av一级在线观看 | 黄色片免费观看 | 欧美一级免费看 | 久久综合99 | 欧美性猛片aaaaaaa做受 | 九九久久精品 | 污片在线免费看 | 国产高清精品在线 | 亚洲射情 | 精品一区二区免费视频 | 欧美日韩中文在线观看 | 免费观看h片 | 欧美激情精品久久久久久 | 免费一级片在线 | 国产亚洲欧美在线 | 久久久久久久久国产 | 久久亚洲精品中文字幕 | 成人在线观看免费 | 青青国产视频 | 久久99精品久久久久久 | 伊人五月 | 性免费网站 | 一区二区三区四区在线 | 中文字幕一区二区三区四区五区 | 国产欧美综合一区二区三区 | 欧美日韩一区二区三区在线电影 | av在线播放网站 | 欧美福利二区 | 国产综合视频 | 亚洲精品在线播放视频 | 日韩专区视频 | 久久蜜桃精品一区二区三区综合网 | 国产福利一区二区三区四区 | 亚洲成人一区二区三区 | 私人毛片免费高清视频 | sis001亚洲原创区 | 国产黄色a级 | 亚洲免费在线观看 | 日韩欧美一区二区三区 |