id: field title:

custom_edit_url: https://github.com/jaredpalmer/formik/edit/master/docs/api/field.md

<Field />将自动连接到 Formik 的输入。它使用了name属性与 Formik 状态匹配。<Field />将默认为 HTML<input />元件。

场渲染道具

有 3 种方法可以渲染<Field>

  • <Field component>
  • <Field render>
  • <Field children>

除了字符串之外component,为了您的方便,每个渲染道具都传递相同的道具。

Field 的渲染道具是一个包含以下内容的对象:

  • field:包含的对象onChangeonBlurname,和value领域的
  • form:Formik 包。
  • 任何其他道具传递到现场

  1. import React from 'react';
  2. import {Formik, Field} from 'formik';
  3. const Example = () => (
  4. <div>
  5. <h1>My Form</h1>
  6. <Formik
  7. initialValues={{email: '', color: 'red', firstName: ''}}
  8. onSubmit={(values, actions) => {
  9. setTimeout(() => {
  10. alert(JSON.stringify(values, null, 2));
  11. actions.setSubmitting(false);
  12. }, 1000);
  13. }}
  14. render={(props: FormikProps<Values>) => (
  15. <form onSubmit={props.handleSubmit}>
  16. <Field type="email" name="email" placeholder="Email" />
  17. <Field component="select" name="color">
  18. <option value="red">Red</option>
  19. <option value="green">Green</option>
  20. <option value="blue">Blue</option>
  21. </Field>
  22. <Field name="firstName" component={CustomInputComponent} />
  23. <Field
  24. name="lastName"
  25. render={({field /* _form */}) => (
  26. <input {...field} placeholder="lastName" />
  27. )}
  28. />
  29. <button type="submit">Submit</button>
  30. </form>
  31. )}
  32. />
  33. </div>
  34. );
  35. const CustomInputComponent = ({
  36. field, // { name, value, onChange, onBlur }
  37. form: {touched, errors}, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
  38. ...props
  39. }) => (
  40. <div>
  41. <input type="text" {...field} {...props} />
  42. {touched[field.name] && errors[field.name] && (
  43. <div className="error">{errors[field.name]}</div>
  44. )}
  45. </div>
  46. );

道具

\


参考

道具

children

children?: React.ReactNode | ((props: FieldProps) => React.ReactNode)

无论是 JSX 元素还是回调函数。与…一样render

  1. // Children can be JSX elements
  2. <Field name="color" component="select" placeholder="Favorite Color">
  3. <option value="red">Red</option>
  4. <option value="green">Green</option>
  5. <option value="blue">Blue</option>
  6. </Field>
  7. // Or a callback function
  8. <Field name="firstName">
  9. {({ field, form }) => (
  10. <div>
  11. <input type="text" {...field} placeholder="First Name"/>
  12. {form.touched[field.name] &&
  13. form.errors[field.name] && <div className="error">{form.errors[field.name]}</div>}
  14. </div>
  15. )}
  16. </Field>

component

component?: string | React.ComponentType<FieldProps>

要么是 React 组件,要么是要呈现的 HTML 元素的名称。也就是说,以下之一:

  • input
  • select
  • textarea
  • 自定义的 React 组件

将传递自定义反应组件FieldProps这是一样的render支柱参数<Field render>加上任何其他道具直接传递到<Field>

默认是'input'(所以<input>默认情况下呈现)

  1. // Renders an HTML <input> by default
  2. <Field name="lastName" placeholder="Last Name"/>
  3. // Renders an HTML <select>
  4. <Field name="color" component="select" placeholder="Favorite Color">
  5. <option value="red">Red</option>
  6. <option value="green">Green</option>
  7. <option value="blue">Blue</option>
  8. </Field>
  9. // Renders a CustomInputComponent
  10. <Field name="firstName" component={CustomInputComponent} placeholder="First Name"/>
  11. const CustomInputComponent = ({
  12. field, // { name, value, onChange, onBlur }
  13. form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
  14. ...props
  15. }) => (
  16. <div>
  17. <input type="text" {...field} {...props} />
  18. {touched[field.name] &&
  19. errors[field.name] && <div className="error">{errors[field.name]}</div>}
  20. </div>
  21. );

innerRef

innerRef?: (el: React.HTMLElement<any> => void)

当你是使用自定义组件,您需要访问由其创建的基础 DOM 节点Field(例如打电话focus),将回调传递给innerRef反而道具。

name

name: string 需要

Formik 状态下的字段名称。要访问嵌套对象或数组,name 也可以接受像 lodash 一样的点路径social.facebook要么friends[0].firstName

render

render?: (props: FieldProps) => React.ReactNode

一个返回一个或多个 JSX 元素的函数。

  1. // Renders an HTML <input> and passes FieldProps field property
  2. <Field
  3. name="firstName"
  4. render={({ field /* { name, value, onChange, onBlur } */ }) => (
  5. <input {...field} type="text" placeholder="firstName" />
  6. )}
  7. />
  8. // Renders an HTML <input> and disables it while form is submitting
  9. <Field
  10. name="lastName"
  11. render={({ field, form: { isSubmitting } }) => (
  12. <input {...field} disabled={isSubmitting} type="text" placeholder="lastName" />
  13. )}
  14. />
  15. // Renders an HTML <input> with custom error <div> element
  16. <Field
  17. name="lastName"
  18. render={({ field, form: { touched, errors } }) => (
  19. <div>
  20. <input {...field} type="text" placeholder="lastName" />
  21. {touched[field.name] &&
  22. errors[field.name] && <div className="error">{errors[field.name]}</div>}
  23. </div>
  24. )}
  25. />

validate

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

您可以通过将函数传递给,来运行独立的字段级验证validate支柱。该功能将尊重validateOnBlurvalidateOnChange在/中指定的配置/道具<Field>'s<Formik>/withFormik。此函数可以是同步函数,也可以是异步函数:

  • 同步:如果无效,则返回 astring包含错误消息或返回undefined

  • 异步:返回一个抛出一个的 Promisestring包含错误消息。这就像 Formik 一样validate,而不是返回errors对象,它只是一个string

  1. import React from 'react';
  2. import {Formik, Form, Field} from 'formik';
  3. // Synchronous validation function
  4. const validate = value => {
  5. let errorMessage;
  6. if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
  7. errorMessage = 'Invalid email address';
  8. }
  9. return errorMessage;
  10. };
  11. // Async validation function
  12. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  13. const validateAsync = value => {
  14. return sleep(2000).then(() => {
  15. if (['admin', 'null', 'god'].includes(value)) {
  16. throw 'Nice try';
  17. }
  18. });
  19. };
  20. // example usage
  21. const MyForm = () => (
  22. <Formik
  23. initialValues={{email: '', username: ''}}
  24. onSubmit={values => alert(JSON.stringify(values, null, 2))}
  25. >
  26. {({errors, touched}) => (
  27. <Form>
  28. <Field validate={validate} name="email" type="email" />
  29. {errors.email && touched.email ? <div>{errors.email}</div> : null}
  30. <Field validate={validateAsync} name="username" />
  31. {errors.username && touched.username ? (
  32. <div>{errors.username}</div>
  33. ) : null}
  34. <button type="submit">Submit</button>
  35. </Form>
  36. )}
  37. </Formik>
  38. );

注意:要允许 i18n 库,可以使用 TypeScript 类型validate略微放松,让你返回一个Function(例如。i18n('invalid'))。