使用Formik轻松开发更高质量的React表单(四)其他几个API解析

2021-03-26 05:26

阅读:679

标签:event   round   isp   message   higher   data   ali   options   ike   

(下面部分内容正处于翻译中,敬请稍等......)

will automagically hook up inputs to Formik. It uses the name attribute to match up with Formik state. will default to an element. To change the underlying element of , specify a component prop. It can either be a string like select or another React component. can also take a render prop.

import React from ‘react‘;
import { Formik, Field } from ‘formik‘;

const Example = () => (
  

My Form

{ setTimeout(() => { alert(JSON.stringify(values, null, 2)); actions.setSubmitting(false); }, 1000); }} render={(props: FormikProps) => (
( )} />
)} />
); const CustomInputComponent: React.SFC & CustomInputProps > = ({ field, // { name, value, onChange, onBlur } form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => (
{touched[field.name] && errors[field.name] &&
{errors[field.name]}
}
);

validate?: (value: any) => undefined | string | Promise

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 ‘s parent / withFormik. This function can be either be:

Synchronous and if invalid, return a string containing the error message or return undefined.

// 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: 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

// 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‘;
    }
  });
};

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‘)).

Refs

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.

is a component that helps with common array/list manipulations. You pass it a name property with the path to the key within values that holds the relevant array. will then give you access to array helper methods via render props. For convenience, calling these methods will trigger validation and also manage touched for you.

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

setTimeout(() => { alert(JSON.stringify(values, null, 2)); }, 500) } render={({ values }) => (
(
{values.friends && values.friends.length > 0 ? ( values.friends.map((friend, index) => (
)) ) : ( )}
)} />
)} />
);

name: string

The name or path to the relevant key in values.

validateOnChange?: boolean

Default is true. Determines if form validation should or should not be run after any array manipulations.

FieldArray Array of Objects

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 or elements in .

(
{values.friends.map((friend, index) => (
// both these conventions do the same
))}
)} />

FieldArray Validation Gotchas

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,

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‘),
});

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)...

Bad

// within a `FieldArray`‘s render
const FriendArrayErrors = errors =>
  errors.friends ? 
{errors.friends}
: null; // app will crash

Good

// within a FieldArray‘s render

const FriendArrayErrors = errors =>
  typeof errors.friends === ‘string‘ ? 
{errors.friends}
: null;

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 component that looks like this:

import { Field, getIn } from ‘formik‘;

const ErrorMessage = ({ name }) => (
   {
      const error = getIn(form.errors, name);
      const touch = getIn(form.touched, name);
      return touch && error ? error : null;
    }}
  />
);
// Usage
; // => null, ‘too short‘, or ‘required‘

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.

FieldArray Helpers

The following methods are made available via render props.

  • push: (obj: any) => void: Add a value to the end of an array**
  • swap: (indexA: number, indexB: number) => void: Swap two values in an array
  • move: (from: number, to: number) => void: Move an element in an array to another index
  • insert: (index: number, value: any) => void: Insert an element at a given index into the array
  • unshift: (value: any) => number: Add an element to the beginning of an array and return its length
  • remove(index: number): T | undefined: Remove an element at an index of an array and return it
  • pop(): T | undefined: Remove and return value from the end of the array**

FieldArray render methods

There are three ways to render things with


render: (arrayHelpers: ArrayHelpers) => React.ReactNode
import React from ‘react‘;
import { Formik, Form, Field, FieldArray } from ‘formik‘

export const FriendList = () => (
  

Friend List

( (
{/*... use these however you want */}
)} /> />
);

component: React.ReactNode

import React from ‘react‘;
import { Formik, Form, Field, FieldArray } from ‘formik‘

export const FriendList = () => (
  

Friend List

( />
); // In addition to the array helpers, Formik state and helpers // (values, touched, setXXX, etc) are provided through a `form` // prop export const MyDynamicForm = ({ move, swap, push, insert, unshift, pop, form }) => (
{/** whatever you need to do */}
);



Like ,

is a helper component you can use to save time. It is tiny wrapper around
. This means you don‘t need to explictly type out
if you don‘t want to.

ReactDOM only

import React from ‘react‘;
import { Formik, Field, Form } from ‘formik‘;

const Example = () => (
  

My Form

{ setTimeout(() => { alert(JSON.stringify(values, null, 2)); actions.setSubmitting(false); }, 1000); }} component={MyForm} />
); const MyForm = () => (
);

withFormik(options)

Create a higher-order React component class that passes props and form handlers (the "FormikBag") into your component derived from supplied options.

options

displayName?: string

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 {..}).

enableReinitialize?: boolean

Default is false. Control whether Formik should reset the form if the wrapped component props change (using deep equality).

handleSubmit: (values: Values, formikBag: FormikBag) => void

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 + resetForm) and any props that were passed to the the wrapped component.

The "FormikBag":
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

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.

mapPropsToValues?: (props: Props) => Values

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.

validate?: (values: Values, props: Props) => FormikErrors | Promise

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:

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;
};

Asynchronous and return a Promise that‘s error is an errors object

// 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

Default is true. Use this option to run validations on blur events. More specifically, when either handleBlur, setFieldTouched, or setTouched are called.

validateOnChange?: boolean

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.

validationSchema?: Schema | ((props: Props) => Schema)

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.

Injected props and methods

These are identical to the props of ...} />

在Formik中使用connect()

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 , , and

. Advanced users may find it useful to use connect() when building custom components.

import { connect } from ‘formik‘;

const SubmitCount = ({ formik }) => 
{formik.submitCount}
; export default connect(SubmitCount);

使用Formik轻松开发更高质量的React表单(四)其他几个API解析

标签:event   round   isp   message   higher   data   ali   options   ike   

原文地址:http://blog.51cto.com/zhuxianzhong/2152020


评论


亲,登录后才可以留言!