React+AntdUi实现《好客租房系统》登陆验证06

一、分为三个部分,顶部导航、表单和底部文字,顶部表单已经封装好,而底部文字是固定的

 

 表单使用formilk组件实现,而表单验证使用withFormik组件验证

<div className={styles.root}>
        {/* 顶部导航 */}
        <NavBar mode="light">
          账号登录
        </NavBar>
        <WhiteSpace size="xl" />

        {/* 登录表单 */}
        <WingBlank>
          <form onSubmit={handleSubmit}>
            <div className={styles.formItem}>
              <input
                className={styles.input}
                name="username"
                value={values.username}
                onChange={handleChange}
                placeholder="请输入账号"
              />
            </div>
            {/* 长度为5到8位,只能出现数字、字母、下划线 */}
            {errors.username && <div className={styles.error}>{errors.username}</div>}
            <div className={styles.formItem}>
              <input
                className={styles.input}
                name="password"
                type="password"
                value={values.password}
                onChange={handleChange}
                placeholder="请输入密码"
              />
            </div>
            {/* 长度为5到12位,只能出现数字、字母、下划线 */}
            {errors.password && <div className={styles.error}>{errors.password}</div>}
            <div className={styles.formSubmit}>
              <button className={styles.submit} type="submit">
                登 录
              </button>
            </div>
          </form>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <Link to="/registe">还没有账号,去注册~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )

  

export default withFormik({
  // 提供表单的状态数据和当前表单的input的name属性值一一对应
  mapPropsToValues: () => ({ username: 'test2', password: 'test2' }),
  // 验证表单
  validationSchema: yup.object().shape({
    username: yup.string().required('账号为必填项!').matches(REG_UNAME, '账号长度为5到8位,只能出现数字、字母、下划线'),
    password: yup.string().required('密码为必填项!').matches(REG_PWD, '密码长度为5到12位,只能出现数字、字母、下划线'),
  }),
  // 处理表单提交
  // handleSubmit: (values: Values, formikBag: FormikBag) => void | Promise<any>
  handleSubmit: async (values, formikBag) => {
    console.log(formikBag)
    const { username, password } = values;
    console.log(username, password)
    let data = {
      username,
      password
    }
    let res = await login(data);
    console.log(res)
    if (res.status === 200) {
      setToken(res.data.token);
      const { history, location: { state } } = formikBag.props;
      if (state && state.backUrl) {
        history.replace(state.backUrl)
      } else {
        history.go(-1)
      }
    } else {
      Toast.offline(res.description)
    }
  },
})(Login)

  

posted @ 2021-07-31 01:29  AoYeDDM  阅读(109)  评论(0编辑  收藏  举报