1.高阶组件去绑定表单元素,原生的表单元素一个个去绑定表单元素比较繁琐
// 导入withFormik
import { withFormik, Form, Field, ErrorMessage } from 'formik'
{/* 登录表单 */}
<WingBlank>
<Form>
{/* 账号 */}
<div className={styles.formItem}>
<Field
className={styles.input}
name="username"
placeholder="请输入账号"
/>
</div>
<ErrorMessage
className={styles.error}
name="username"
component="div"
/>
{/* 密码 */}
<div className={styles.formItem}>
<Field
className={styles.input}
name="password"
type="password"
placeholder="请输入密码"
/>
</div>
<ErrorMessage
className={styles.error}
name="password"
component="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>
2.yup实现表单元素校验
// 导入Yup
import \* as Yup from 'yup'
// 添加表单校验规则
validationSchema: Yup.object().shape({
username: Yup.string()
.required('账号为必填项')
.matches(REG_UNAME, '长度为5到8位,只能出现数字、字母、下划线'),
password: Yup.string()
.required('密码为必填项')
.matches(REG_PWD, '长度为5到12位,只能出现数字、字母、下划线')
}),
3.登录鉴权,部分页面需要登陆后才能使用
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { isAuth } from '../../utils'
// <AuthRoute path="..." component={...}></AuthRoute>
const AuthRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
const isLogin = isAuth()
if (isLogin) {
// 已登录
// 将 props 传递给组件,组件中才能获取到路由相关信息
return <Component {...props} />
} else {
// 未登录
return (
<Redirect
to={{
pathname: '/login',
state: {
from: props.location
}
}}
/>
)
}
}}
/>
)
}
export default AuthRoute
4.登录成功后返回原来点击前的页面
/*
1 登录成功后,判断是否需要跳转到用户想要访问的页面(判断 props.location.state 是否有值)。
2 如果不需要(没有值),则直接调用 history.go(-1) 返回上一页。
3 如果需要,就跳转到 from.pathname 指定的页面(推荐使用 replace 方法模式,而不是 push)。
*/
if (!props.location.state) {
// 此时,表示是直接进入到了该页面,直接调用 go(-1) 即可
props.history.go(-1)
} else {
// push:[home, login, map]
// replace: [home, map]
props.history.replace(props.location.state.from.pathname)
}