react 新手,刚开始在 react-redux 应用程序上工作。只是想知道是否有人对与表单验证和显示错误消息相关的最佳实践有任何提示?对此的任何想法都非常感谢:)
问问题
1828 次
2 回答
0
The react way is to have a container handle the state and pass it through the props to the inputs (components). So it's not really a react-redux thing to handle a validation, if of course you don't build through multiple routes and need that global state.
于 2018-06-08T08:20:11.870 回答
0
我喜欢在 React 中使用Formik作为表单。主要好处是:
- 验证和错误消息
- 处理表单状态
- 处理表单提交
将Yup(模式验证器)与 Formik一起使用是个好主意。
以下是 Formik + Yup 的表单示例:
yarn add formik yup
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
const SignupSchema = Yup.object().shape({
: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
email: Yup.string()
.email('Invalid email')
.required('Required'),
});
export const ValidationSchemaExample = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
name: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="name" />
{errors.name && touched.name ? (
<div>{errors.name}</div>
) : null}
<Field name="email" type="email" />
{errors.email && touched.email ? <div>{errors.email}</div> : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
于 2020-04-16T09:34:46.120 回答