AntDesign(React)学习-4 登录页面提交数据简单实现

github代码:https://github.com/zhaogaojian/jgdemo

全国肺炎,过节期间没地方去在家学习antd。

一、感觉antd pro项目太庞大了,可以学习下结构和代码风格,但不适合新手直接学习测试语法用,将从一个空白项目开始创建

1、打开umi管理后台,创建一个新项目

 

 

 

 2、umi会自动安装各种依赖项,进行项目创建

 

 3、项目结构如下,将仿照antd做一个登录页面

 

二、实现登录页面

创建了不包含antd演示的jgdemo项目,以后改使用vscode编辑代码,创建user,login目录

 

 

 2、点击start可以直接启动项目

 

 

 3、安装antd组件

 

 

 4、antd官网

https://ant.design/docs/react/introduce-cn

蚂蚁金服的技术网站,在老家破网打开速度特别慢!

修改index.tsx代码如下

 

 

 运行效果如下

 

 

 

5、为了省事,直接在index上做登录了,增加两个input输入框,最终tsx代码如下。

import React from 'react';
import styles from './index.css';
import { Button,Input } from 'antd';
export default function() {
  return (
    <div className={styles.normal}>
      <table style={{margin:"0 auto",width:300}}>
        <tr>
        <td>用户名:</td>
        <td><Input placeholder="请输入用户名" style={{width:200}}/></td>
        </tr>
        <tr>
        <td>密码:</td>
        <td><Input.Password placeholder="请输入密码" style={{width:200}}/></td>
        </tr>
      </table>
      <Button type="primary" style={{marginTop:10,width:300}}>登录</Button>
    </div>
  );
}

注意不能直接写style="width:200px",margin后面要加双引号

运行效果如下

 6、网上一般的写法是使用组件,index.tsx代码继续完善,

mock下增加一个login.ts文件,模拟post数据

import { Request, Response } from 'express';
export default {
    'POST /api/login': (req: Request, res: Response) => {
        res.send({ status: 'ok', token: '121131323' });
      },
  };

提交数据代码如下

import React from 'react';
import styles from './index.css';
import Link from 'umi/link';
import { Button,Input} from 'antd';
import Password from 'antd/lib/input/Password';
class index extends React.Component{ 
  constructor(props) {
    super(props);
    this.state={
      userName:'test',
      passWord:'123456'
    }
  }
  state:{
    userName,
    passWord
  }
  login(){
    var userName = this.state.userName;
    var passWord = this.state.passWord;
    const postData ={
      userName:userName,
      passWord:passWord
    };
    console.log(postData);
    fetch('http://localhost:8000/api/login',{
            // post提交
            method:"POST",
            headers:{
                "Content-type":"application/json"
            },
            body:JSON.stringify(postData)//把提交的内容转字符串
        })
        .then(res =>res.json())
        .then(data =>{
            console.log(data)
        })
  };
  handleUserNameChange=(event)=>{
    this.setState({userName: event.target.value});
    console.log(this.state.userName);
  }
  handlePassWordChange(event){
    //this.state.passWord=event.target.value;//错误用法,这样passWord value不会更新
    this.setState({passWord: event.target.value});
  }
  render() {
    return (
      <div className={styles.normal}>
        <table style={{margin:"0 auto",width:300}}>
          <tbody>
          <tr>
          <td>用户名:</td>
          <td><Input placeholder="请输入用户名" id="userName" value={this.state.userName} style={{width:200}} onChange={this.handleUserNameChange}/></td>
          </tr>
          <tr>
          <td>密码:</td>
          <td><Input.Password placeholder="请输入密码" id="passWord"  value={this.state.passWord} style={{width:200}} onChange={this.handlePassWordChange.bind(this)}/></td>
          </tr>
          </tbody>
        </table>
        <Button type="primary" style={{marginTop:10,width:300}} onClick={()=>(this.login())}>登录</Button>
      </div>
    );
  }
}
export default index;

 为什么使用bind(this)

以下bind(this)讲解来自:https://blog.csdn.net/qq_34829447/article/details/81705977

1.JavaScript自身特性说明
如果传递一个函数名给一个变量,之后通过函数名()的方式进行调用,在方法内部如果使用this则this的指向会丢失。
示例代码:
首先我们创建test对象并直接调用方法 :

const test = {
    name:'jack',
    getName:function(){
        console.log(this.name)
    }
}
test.getName()
使用node test.js执行上述代码可以正常输出jack。 
之后,我们对代码进行调整:

const test = {
    name:'jack',
    getJack:function(){
        console.log(this.name)
    }
}
const func = test.getJack;
func();

我们没有直接调用对象的方法,而是将方法声明给一个中间变量,之后利用中间变量()调用方法,此时this则失去指向,输出undefined,如果使用node环境执行js文件则输出node相关信息,如嵌入到html中则this指向window对象
React中的bind同上方原理一致,在JSX中传递的事件不是一个字符串,而是一个函数(如:onClick={this.handleClick}),此时onClick即是中间变量,所以处理函数中的this指向会丢失。解决这个问题就是给调用函数时bind(this),
从而使得无论事件处理函数如何传递,this指向都是当前实例化对象。 
当然,如果不想使用bind(this),我们可以在声明函数时使用箭头函数将函数内容返回给一个变量,并在调用时直接使用this.变量名即可

 

7、在React中也可以使用getElementById方式获取数据(实际开发中尽量不要使用这种方式)。

import React from 'react';
import styles from './index.css';
import { Button,Input } from 'antd';
export const LOGIN = {
  login:function(){
    var userName = (document.getElementById('userName') as HTMLInputElement)?.value;
    var passWord = (document.getElementById('passWord') as HTMLInputElement)?.value;
    const postData ={
      userName:userName,
      passWord:passWord
    };
    fetch('http://localhost:8000/api/login',{
            // post提交
            method:"POST",
            headers:{
                "Content-type":"application/json"
            },
            body:JSON.stringify(postData)//把提交的内容转字符串
        })
        .then(res =>res.json())
        .then(data =>{
            console.log(data)
        })
  }
};
export default function() {
  return (
    <div className={styles.normal}>
      <table style={{margin:"0 auto",width:300}}>
        <tbody>
        <tr>
        <td>用户名:</td>
        <td><Input placeholder="请输入用户名" id="userName" style={{width:200}}/></td>
        </tr>
        <tr>
        <td>密码:</td>
        <td><Input.Password placeholder="请输入密码" id="passWord" style={{width:200}}/></td>
        </tr>
        </tbody>
      </table>
      <Button type="primary" style={{marginTop:10,width:300}} onClick={()=>(LOGIN.login())}>登录</Button>
    </div>
  );
}

这样,点击登录按钮即可post数据到服务端后台

 

posted @ 2020-01-28 16:26  zhaogaojian  阅读(4211)  评论(0编辑  收藏  举报