react form

Last updated on November 20, 2024 am

🧙 Questions

使用 react-hook-form

☄️ Ideas

npm install react-hook-form
import React, {useState} from "react";
import {Button, Input} from "../../../react-keycap";
import Icon from "../../assets/icons";
import {useNavigate} from "react-router-dom";
import {_getUserInfo, _userSignIn} from "../../services/apis-user";
import {SubmitHandler, useForm} from "react-hook-form";

type Inputs = {
  account: string,
  password: string,
};

export default function Login() {

  const logoUrl = "https://img.isxcode.com/isxcode_img/leo/favicon.ico";
  const navigate = useNavigate();

  const { register, handleSubmit, watch, formState: { errors } } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = data => {
    _userSignIn(data).then(res => {
      localStorage.setItem("Authorization", res.data.accessToken)
      localStorage.setItem("RefreshToken", res.data.refreshToken)
      _getUserInfo().then(res => {
        localStorage.setItem("UserInfo", JSON.stringify(res.data));
        console.log(JSON.parse(localStorage.getItem('UserInfo')));
        navigate("/todo");
      });
    });
  }

  return <>

    <img className={"logo"} src={logoUrl} alt={"logo"} onClick={() => navigate("/")}/>

    <div className={"login-input"}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Input cap={"line"} placeholder={"account"} type={"text"} {...register("account", {
          required: true,
          pattern: /^[A-Za-z]+$/i,
          maxLength: 20})} />
        {errors.account?.type === 'required' && <p role="alert">account is required</p>}
        {errors.account?.type === 'pattern' && <p role="alert">account is pattern</p>}
        {errors.account?.type === 'maxLength' && <p role="alert">account is maxLength</p>}
        <Input cap={"line"} placeholder={"password"} type={"password"} {...register("password", {required: true})} />
        {errors.password && <span>This field is required</span>}
        <Button label={"Sign in"} type="submit"/>
      </form>
    </div>

  </>;
};

react form
https://ispong.isxcode.com/vue/react/react form/
Author
ispong
Posted on
October 24, 2022
Licensed under