<Field />

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

¥<Field /> will automagically hook up inputs to Formik. It uses the name attribute to match up with Formik state. <Field /> will default to an HTML <input /> element.

渲染

¥Rendering

有几种不同的方法可以使用 <Field> 渲染事物。

¥There are a few different ways to render things with <Field>.

  • <Field as>

  • <Field children>

  • <Field component>

  • <Field render> 在 2.x 中已弃用。使用这些将记录警告

    ¥<Field render> deprecated in 2.x. Using these will log warning

as 可以是 React 组件,也可以是要渲染的 HTML 元素的名称。Formik 会自动将 name 属性指定的字段的 onChangeonBlurnamevalue 属性注入到(自定义)组件。

¥as can either be a React component or the name of an HTML element to render. Formik will automagically inject onChange, onBlur, name, and value props of the field designated by the name prop to the (custom) component.

children 可以是元素数组(例如 <Field as="select"> 中的 <option>)或回调函数(也称为 render prop)。渲染属性是一个包含以下内容的对象:

¥children can either be an array of elements (e.g. <option> in the case of <Field as="select">) or a callback function (a.k.a render prop). The render props are an object containing:

  • field:包含字段 onChangeonBlurnamevalue 的对象(参见 FieldInputProps

    ¥field: An object containing onChange, onBlur, name, and value of the field (see FieldInputProps)

  • form:Formik 包

    ¥form: The Formik bag

  • meta:包含有关字段的元数据(即 valuetouchederrorinitialValue)的对象(参见 FieldMetaProps

    ¥meta: An object containing metadata (i.e. value, touched, error, and initialValue) about the field (see FieldMetaProps)

component 可以是 React 组件,也可以是要渲染的 HTML 元素的名称。所有附加属性都将被传递。

¥component can either be a React component or the name of an HTML element to render. All additional props will be passed through.

在 Formik 0.9 到 1.x 中,render 属性也可以用于渲染。自 2.x 以来它已被弃用。虽然代码仍然存在于 <Field> 中,但使用 render 会在控制台中显示警告。

¥In Formik 0.9 to 1.x, the render prop could also be used for rendering. It has been deprecated since 2.x. While the code still lives within <Field>, using render will show a warning in the console.

示例

¥Example

import React from 'react';
import { Field, Form, Formik, FormikProps } from 'formik';
const MyInput = ({ field, form, ...props }) => {
return <input {...field} {...props} />;
};
const Example = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ email: '', color: 'red', firstName: '', lastName: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{(props: FormikProps<any>) => (
<Form>
<Field type="email" name="email" placeholder="Email" />
<Field as="select" name="color">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
<Field name="lastName">
{({
field, // { name, value, onChange, onBlur }
form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
meta,
}) => (
<div>
<input type="text" placeholder="Email" {...field} />
{meta.touched && meta.error && (
<div className="error">{meta.error}</div>
)}
</div>
)}
</Field>
<Field name="lastName" placeholder="Doe" component={MyInput} />
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);

属性

¥Props


参考

¥Reference

属性

¥Props

as

as?: string | React.ComponentType<FieldProps['field']>

React 组件或要渲染的 HTML 元素的名称。即,以下之一:

¥Either a React component or the name of an HTML element to render. That is, one of the following:

  • input

  • select

  • textarea

  • 有效的 HTML 元素名称

    ¥A valid HTML element name

  • 自定义 React 组件

    ¥A custom React component

自定义 React 组件将传递 onChangeonBlurnamevalue 以及直接传递给 <Field> 的任何其他 props。

¥Custom React components will be passed onChange, onBlur, name, and value plus any other props passed directly to <Field>.

默认为 'input'(因此默认渲染 <input>

¥Default is 'input' (so an <input> is rendered by default)

// Renders an HTML <input> by default
<Field name="lastName" placeholder="Last Name"/>
// Renders an HTML <select>
<Field name="color" as="select">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
// Renders a CustomInputComponent
<Field name="firstName" as={CustomInputComponent} placeholder="First Name"/>
const CustomInputComponent = (props) => (
<input className="my-custom-input" type="text" {...props} />
);

children

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

JSX 元素或回调函数。与 render 相同。

¥Either JSX elements or callback function. Same as render.

// Children can be JSX elements
<Field name="color" as="select">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
// Or a callback function
<Field name="firstName">
{({ field, form, meta }) => (
<div>
<input type="text" {...field} placeholder="First Name"/>
{meta.touched &&
meta.error && <div className="error">{meta.error}</div>}
</div>
)}
</Field>

component

component?: string | React.ComponentType<FieldProps>

React 组件或要渲染的 HTML 元素的名称。即,以下之一:

¥Either a React component or the name of an HTML element to render. That is, one of the following:

  • input

  • select

  • textarea

  • 自定义 React 组件

    ¥A custom React component

自定义 React 组件将传递 FieldProps,它与 <Field render>render 属性参数相同,加上直接传递给 <Field> 的任何其他属性。

¥Custom React components will be passed FieldProps which is same render prop parameters of <Field render> plus any other props passed to directly to <Field>.

默认为 'input'(因此默认渲染 <input>

¥Default is 'input' (so an <input> is rendered by default)

// Renders an HTML <input> by default
<Field name="lastName" placeholder="Last Name"/>
// Renders an HTML <select>
<Field name="color" component="select">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
// Renders a CustomInputComponent
<Field name="firstName" component={CustomInputComponent} placeholder="First Name"/>
const CustomInputComponent = ({
field, // { name, value, onChange, onBlur }
form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
...props
}) => (
<div>
<input type="text" {...field} {...props} />
{touched[field.name] &&
errors[field.name] && <div className="error">{errors[field.name]}</div>}
</div>
);

innerRef

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

当你不使用自定义组件并且需要访问由 Field 创建的底层 DOM 节点(例如调用 focus)时,请将回调传递给 innerRef 属性。

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

name

name: string

必需的

¥Required

Formik 状态的字段名称。要访问嵌套对象或数组,名称还可以接受类似于 lodash 的点路径,如 social.facebookfriends[0].firstName

¥A field's name in Formik state. To access nested objects or arrays, name can also accept lodash-like dot path like social.facebook or friends[0].firstName

render

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

在 2.x 中已弃用。请改用 children

¥Deprecated in 2.x. Use children instead.

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

¥A function that returns one or more JSX elements.

// Renders an HTML <input> and passes FieldProps field property
<Field
name="firstName"
render={({ field /* { name, value, onChange, onBlur } */ }) => (
<input {...field} type="text" placeholder="firstName" />
)}
/>
// Renders an HTML <input> and disables it while form is submitting
<Field
name="lastName"
render={({ field, form: { isSubmitting } }) => (
<input {...field} disabled={isSubmitting} type="text" placeholder="lastName" />
)}
/>
// Renders an HTML <input> with custom error <div> element
<Field
name="lastName"
render={({ field, form: { touched, errors } }) => (
<div>
<input {...field} type="text" placeholder="lastName" />
{touched[field.name] &&
errors[field.name] && <div className="error">{errors[field.name]}</div>}
</div>
)}
/>

validate

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

你可以通过将函数传递给 validate 属性来运行独立的字段级验证。该函数将遵循 <Field>'s 父级 <Formik> / withFormik 中指定的 validateOnBlurvalidateOnChange 配置/属性。该函数可以是同步的,也可以是异步的:

¥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 <Field>'s parent <Formik> / withFormik. This function can either be synchronous or asynchronous:

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

    ¥Sync: if invalid, return a string containing the error message or return undefined.

  • 异步:返回一个 Promise,该 Promise 解析包含错误消息的 string。这与 Formik 的 validate 类似,但不是返回 errors 对象,而是返回 string

    ¥Async: return a Promise that resolves a string containing the error message. This works like Formik's validate, but instead of returning an errors object, it's just a string.

import React from 'react';
import { Formik, Form, Field } from 'formik';
// Synchronous validation function
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 function
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validateAsync = value => {
return sleep(2000).then(() => {
if (['admin', 'null', 'god'].includes(value)) {
return 'Nice try';
}
});
};
// example usage
const MyForm = () => (
<Formik
initialValues={{ email: '', username: '' }}
onSubmit={values => alert(JSON.stringify(values, null, 2))}
>
{({ errors, touched }) => (
<Form>
<Field validate={validate} name="email" type="email" />
{errors.email && touched.email ? <div>{errors.email}</div> : null}
<Field validate={validateAsync} name="username" />
{errors.username && touched.username ? (
<div>{errors.username}</div>
) : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
);

注意:为了允许 i18n 库,validate 的 TypeScript 类型稍微放宽,并允许你返回 Function(例如 i18n('invalid'))。

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

Formik 中文网 - 粤ICP备13048890号