react+typrscript+hook+mobx+react-hook-form的表单使用

react+typrscript+hook+mobx+react-hook-form的表单使用

//编辑或添加用户
import React, { useEffect, useState } from "react";
import "./index.scss";
import { Link } from "react-router-dom";
import { observer, inject } from "mobx-react";
import { emailReg } from "../../configs/apiConfig";
import { useForm, Resolver } from "react-hook-form";
import { addUser } from "../api";

type FormValues = {
  username: string;
  email: string;
  password_1: string;
  password_2: string;
  role: "master" | "friend";
  status: "0" | "1";
};

const regQuery=(values:FormValues)=>{
  let _errors:any={}
  if(values.username==""){
    _errors["username"]={
      type: "required",
      message:"用户名不能为空"

    }
  }
  if(!emailReg.test(values.email)){
    _errors['email']={
      type: "required",
      message: "邮箱格式不正确",
    }
  }
  if(values.password_1 !== values.password_2){
    _errors['password_2']={
      type: "required",
      message: "两次密码不相同"
    }
  }
  return _errors
}

const resolver: Resolver<FormValues> = async (values) => {
  return {
    values: values.password_2 ? values : {},
    errors:{...regQuery(values)}
     
  };
};

const AddUser: React.FC = (props: any): React.ReactElement => {
  const { register, handleSubmit, errors } = useForm<FormValues>({ resolver });

  const onSubmit = (data: FormValues) => {
    addUser(data);
    console.log(data);
  };

  return (
    <div className="full-screen">
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          用户名:
          <input name="username" ref={register({ required: true })} />
          {errors?.username && <p>{errors.username.message}</p>}
        </div>
        <div>
          邮箱:
          <input
            name="email"
            type="text"
            ref={register({ required: true, pattern: emailReg })}
          />
          {errors?.email && <p>{errors.email.message}</p>}
        </div>
        <div>
          密码:
          <input
            name="password_1"
            type="password"
            ref={register({ required: true, maxLength: 10 })}
          />
        </div>
        <div>
          确认密码:
          <input
            name="password_2"
            type="password"
            ref={register({ required: true, maxLength: 10 })}
          />
          {errors?.password_2 && <p>{errors.password_2.message}</p>}
        </div>
        <div>
          角色:
          <select name="role" ref={register}>
            <option value="master">master</option>
            <option value="friend">friend</option>
          </select>
        </div>
        <div>
          是否禁用:
          <select name="status" ref={register}>
            <option value="1">是</option>
            <option value="0">否</option>
          </select>
        </div>
        <input type="submit" />
      </form>
    </div>
  );
};

export default AddUser;

posted @ 2020-08-18 15:45  ellenxx  阅读(514)  评论(0编辑  收藏  举报