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
:包含的对象onChange
,onBlur
,name
,和value
领域的form
:Formik 包。- 任何其他道具传递到现场
例
import React from 'react';
import {Formik, Field} from 'formik';
const Example = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{email: '', color: 'red', firstName: ''}}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
render={(props: FormikProps<Values>) => (
<form onSubmit={props.handleSubmit}>
<Field type="email" name="email" placeholder="Email" />
<Field component="select" name="color">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
<Field name="firstName" component={CustomInputComponent} />
<Field
name="lastName"
render={({field /* _form */}) => (
<input {...field} placeholder="lastName" />
)}
/>
<button type="submit">Submit</button>
</form>
)}
/>
</div>
);
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>
);
道具
\
参考
道具
children
children?: React.ReactNode | ((props: FieldProps) => React.ReactNode)
无论是 JSX 元素还是回调函数。与…一样render
。
// Children can be JSX elements
<Field name="color" component="select" placeholder="Favorite Color">
<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 }) => (
<div>
<input type="text" {...field} placeholder="First Name"/>
{form.touched[field.name] &&
form.errors[field.name] && <div className="error">{form.errors[field.name]}</div>}
</div>
)}
</Field>
component
component?: string | React.ComponentType<FieldProps>
要么是 React 组件,要么是要呈现的 HTML 元素的名称。也就是说,以下之一:
input
select
textarea
- 自定义的 React 组件
将传递自定义反应组件FieldProps
这是一样的render
支柱参数<Field render>
加上任何其他道具直接传递到<Field>
。
默认是'input'
(所以<input>
默认情况下呈现)
// Renders an HTML <input> by default
<Field name="lastName" placeholder="Last Name"/>
// Renders an HTML <select>
<Field name="color" component="select" placeholder="Favorite Color">
<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)
当你是不使用自定义组件,您需要访问由其创建的基础 DOM 节点Field
(例如打电话focus
),将回调传递给innerRef
反而道具。
name
name: string
需要
Formik 状态下的字段名称。要访问嵌套对象或数组,name 也可以接受像 lodash 一样的点路径social.facebook
要么friends[0].firstName
render
render?: (props: FieldProps) => React.ReactNode
一个返回一个或多个 JSX 元素的函数。
// 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
支柱。该功能将尊重validateOnBlur
和validateOnChange
在/中指定的配置/道具<Field>'s
亲<Formik>
/withFormik
。此函数可以是同步函数,也可以是异步函数:
同步:如果无效,则返回 a
string
包含错误消息或返回undefined
。异步:返回一个抛出一个的 Promise
string
包含错误消息。这就像 Formik 一样validate
,而不是返回errors
对象,它只是一个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)) {
throw '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 库,可以使用 TypeScript 类型validate
略微放松,让你返回一个Function
(例如。i18n('invalid')
)。