使用Formik轻松开发更高质量的React表单(四)其他几个API解析
2021-03-26 05:26
标签:event round isp message higher data ali options ike You can run independent field-level validations by passing a function to the validate prop. The function will respect the validateOnBlur and validateOnChange config/props specified in the Synchronous and if invalid, return a string containing the error message or return undefined. async: Return a Promise that throws a string containing the error message. This works like Formik‘s validate, but instead of returning an errors object, it‘s just a string. Asynchronous and return a Promise that‘s error is an string with the error message Note: To allow for i18n libraries, the TypeScript typings for validate are slightly relaxed and allow you to return a Function (e.g. i18n(‘invalid‘)). When you are not using a custom component and you need to access the underlying DOM node created by Field (e.g. to call focus), pass the callback to the innerRef prop instead. The name or path to the relevant key in values. Default is true. Determines if form validation should or should not be run after any array manipulations. You can also iterate through an array of objects, by following a convention of object[index]property or object.index.property for the name attributes of Validation can be tricky with If you use validationSchema and your form has array validation requirements (like a min length) as well as nested array field requirements, displaying errors can be tricky. Formik/Yup will show validation errors inside out. For example, Since Yup and your custom validation function should always output error messages as strings, you‘ll need to sniff whether your nested error is an array or a string when you go to display it. So...to display ‘Must have friends‘ and ‘Minimum of 3 friends‘ (our example‘s array validation contstraints)... // within a For the nested field errors, you should assume that no part of the object is defined unless you‘ve checked for it. Thus, you may want to do yourself a favor and make a custom NOTE: In Formik v0.12 / 1.0, a new meta prop may be added to Field and FieldArray that will give you relevant metadata such as error & touch, which will save you from having to use Formik or lodash‘s getIn or checking if the path is defined on your own. The following methods are made available via render props. There are three ways to render things with Like Create a higher-order React component class that passes props and form handlers (the "FormikBag") into your component derived from supplied options. When your inner form component is a stateless functional component, you can use the displayName option to give the component a proper name so you can more easily find it in React DevTools. If specified, your wrapped form will show up as Formik(displayName). If omitted, it will show up as Formik(Component). This option is not required for class components (e.g. class XXXXX extends React.Component {..}). Default is false. Control whether Formik should reset the form if the wrapped component props change (using deep equality). Your form submission handler. It is passed your forms values and the "FormikBag", which includes an object containing a subset of the injected props and methods (i.e. all the methods with names that start with set The "FormikBag": Default is false. Control the initial value of isValid prop prior to mount. You can also pass a function. Useful for situations when you want to enable/disable a submit and reset buttons on initial mount. If this option is specified, then Formik will transfer its results into updatable form state and make these values available to the new component as props.values. If mapPropsToValues is not specified, then Formik will map all props that are not functions to the inner component‘s props.values. That is, if you omit it, Formik will only pass props where typeof props[k] !== ‘function‘, where k is some key. Even if your form is not receiving any props from its parent, use mapPropsToValues to initialize your forms empty state. Note: I suggest using validationSchema and Yup for validation. However, validate is a dependency-free, straightforward way to validate your forms. Validate the form‘s values with function. This function can either be: Asynchronous and return a Promise that‘s error is an errors object Default is true. Use this option to run validations on blur events. More specifically, when either handleBlur, setFieldTouched, or setTouched are called. Default is true. Use this option to tell Formik to run validations on change events and change-related methods. More specifically, when either handleChange, setFieldValue, or setValues are called. A Yup schema or a function that returns a Yup schema. This is used for validation. Errors are mapped by key to the inner component‘s errors. Its keys should match those of values. These are identical to the props of connect()是一个高阶组件,that injects raw Formik context as prop called formik into the inner component. Fun fact: Formik uses connect() under the hood to wire up 使用Formik轻松开发更高质量的React表单(四)其他几个API解析 标签:event round isp message higher data ali options ike 原文地址:http://blog.51cto.com/zhuxianzhong/2152020import React from ‘react‘;
import { Formik, Field } from ‘formik‘;
const Example = () => (
My Form
validate?: (value: any) => undefined | string | Promise
// Synchronous validation for Field
const validate = value => {
let errorMessage;
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
errorMessage = ‘Invalid email address‘;
}
return errorMessage;
};
// Async validation for Field
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validate = value => {
return sleep(2000).then(() => {
if ([‘admin‘, ‘null‘, ‘god‘].includes(value)) {
throw ‘Nice try‘;
}
});
};
Refs
import React from ‘react‘;
import { Formik, Form, Field, FieldArray } from ‘formik‘;
// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
export const FriendList = () => (
Friend List
name: string
validateOnChange?: boolean
FieldArray Array of Objects
FieldArray Validation Gotchas
const schema = Yup.object().shape({
friends: Yup.array()
.of(
Yup.object().shape({
name: Yup.string()
.min(4, ‘too short‘)
.required(‘Required‘), // these constraints take precedence
salary: Yup.string()
.min(3, ‘cmon‘)
.required(‘Required‘), // these constraints take precedence
})
)
.required(‘Must have friends‘) // these constraints are shown if and only if inner constraints are satisfied
.min(3, ‘Minimum of 3 friends‘),
});
Bad
// within a `FieldArray`‘s render
const FriendArrayErrors = errors =>
errors.friends ?
Good
FieldArray
‘s renderconst FriendArrayErrors = errors =>
typeof errors.friends === ‘string‘ ?
import { Field, getIn } from ‘formik‘;
const ErrorMessage = ({ name }) => (
// Usage
FieldArray Helpers
FieldArray render methods
Friend List
component: React.ReactNode
import React from ‘react‘;
import { Formik, Form, Field, FieldArray } from ‘formik‘
export const FriendList = () => (
Friend List
ReactDOM only
import React from ‘react‘;
import { Formik, Field, Form } from ‘formik‘;
const Example = () => (
My Form
withFormik(options)
options
displayName?: string
enableReinitialize?: boolean
handleSubmit: (values: Values, formikBag: FormikBag) => void
props (props passed to the wrapped component)
resetForm
setErrors
setFieldError
setFieldTouched
setFieldValue
setStatus
setSubmitting
setTouched
setValues
Note: errors, touched, status and all event handlers are NOT included in the FormikBag.isInitialValid?: boolean | (props: Props) => boolean
mapPropsToValues?: (props: Props) => Values
validate?: (values: Values, props: Props) => FormikErrors
Synchronous and return an errors object.
// Synchronous validation
const validate = (values, props) => {
let errors = {};
if (!values.email) {
errors.email = ‘Required‘;
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = ‘Invalid email address‘;
}
//...
return errors;
};
// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validate = (values, props) => {
return sleep(2000).then(() => {
let errors = {};
if ([‘admin‘, ‘null‘, ‘god‘].includes(values.username)) {
errors.username = ‘Nice try‘;
}
// ...
if (Object.keys(errors).length) {
throw errors;
}
});
};
validateOnBlur?: boolean
validateOnChange?: boolean
validationSchema?: Schema | ((props: Props) => Schema)
Injected props and methods
在Formik中使用connect()
import { connect } from ‘formik‘;
const SubmitCount = ({ formik }) =>
文章标题:使用Formik轻松开发更高质量的React表单(四)其他几个API解析
文章链接:http://soscw.com/index.php/essay/68061.html