useField()

useField 是一个自定义的 React hook,它将自动帮助你将输入连接到 Formik。你可以而且应该使用它来构建你自己的自定义输入基础类型。有两种使用方法。

¥useField is a custom React hook that will automagically help you hook up inputs to Formik. You can and should use it to build your own custom input primitives. There are 2 ways to use it.

示例

¥Example

import React from 'react';
import { useField, Form, FormikProps, Formik } from 'formik';
interface Values {
firstName: string;
lastName: string;
email: string;
}
const MyTextField = ({ label, ...props }) => {
const [field, meta, helpers] = useField(props);
return (
<>
<label>
{label}
<input {...field} {...props} />
</label>
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</>
);
};
const Example = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{
email: '',
firstName: 'red',
lastName: '',
}}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{(props: FormikProps<Values>) => (
<Form>
<MyTextField name="firstName" type="text" label="First Name" />
<MyTextField name="lastName" type="text" label="Last Name" />
<MyTextField name="email" type="email" label="Email" />
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);

参考

¥Reference

useField<Value = any>(name: string | FieldHookConfig<Value>): [FieldInputProps<Value>, FieldMetaProps<Value>, FieldHelperProps]

一个自定义 React Hook,返回包含 FieldPropsFieldMetaPropsFieldHelperProps 的 3 元组(具有三个元素的数组)。它接受字段名称的字符串或对象作为参数。该对象必须至少包含 name 键。该对象是你将传递给 <Field> 的 props 的子集,FieldProps 中的值和函数将准确模仿 <Field> 的行为。这很有用,而且通常是首选,因为当对象包含相关键/值(例如 type: 'checkbox'multiple: true 等)时,它允许你利用 Formik 的复选框、单选和多选行为。

¥A custom React Hook that returns a 3-tuple (an array with three elements) containing FieldProps, FieldMetaProps and FieldHelperProps. It accepts either a string of a field name or an object as an argument. The object must at least contain a name key. This object is a subset of the props that you would pass to <Field> and the values and functions in FieldProps will mimic the behavior of <Field> exactly. This is useful, and generally preferred, since it allows you to take advantage of Formik's checkbox, radio, and multiple select behavior when the object contains the relevant key/values (e.g. type: 'checkbox', multiple: true, etc.).

FieldMetaProps 包含有关字段的计算值,可用于设置字段样式或以其他方式更改字段。FieldHelperProps 包含辅助程序函数,允许你强制更改字段的值。

¥FieldMetaProps contains computed values about the field which can be used to style or otherwise change the field. FieldHelperProps contains helper functions that allow you to imperatively change a field's values.

import React from 'react';
import { useField } from 'formik';
function MyTextField(props) {
// this will return field props for an <input />
const [field, meta, helpers] = useField(props.name);
return (
<>
<input {...field} {...props} />
{meta.error && meta.touched && <div>{meta.error}</div>}
</>
);
}
function MyInput(props) {
// this will return field exactly like <Field>{({ field }) => ... }</Field>
const [field, meta] = useField(props);
return (
<>
<input {...field} {...props} />
{meta.error && meta.touched && <div>{meta.error}</div>}
</>
);
}
function MyOtherComponent(props) {
// This isn't an input, so instead of using the values in 'field' directly,
// we'll use 'meta' and 'helpers'.
const [field, meta, helpers] = useField(props.name);
const { value } = meta;
const { setValue } = helpers;
const isSelected = v => (v === value ? 'selected' : '');
return (
<div className="itemsPerPage">
<button onClick={() => setValue(5)} className={isSelected(5)}>
5
</button>
<button onClick={() => setValue(10)} className={isSelected(10)}>
10
</button>
<button onClick={() => setValue(25)} className={isSelected(25)}>
25
</button>
</div>
);
}

FieldHookConfig<Value>

该对象是你将传递给 <Field> 的 props 的子集。它包含了:

¥This object is a subset of the props that you would pass to <Field>. It contains:

  • name: string - 字段名称

    ¥name: string - The name of the field

  • validate?: (value: any) => undefined | string | Promise<any> - 参见 <Field> 的文档

    ¥validate?: (value: any) => undefined | string | Promise<any> - See the documentation for <Field>

  • type?: string - HTML 输入的类型(textnumber 等)

    ¥type?: string - The type of the HTML input (text, number and etc.)

  • multiple?: boolean - 是否可以选择多个值。

    ¥multiple?: boolean - Whether or not the multiple values can be selected.

  • value?: string- 仅适用于 checkboxradio 类型的输入。提交表单后,复选框和单选框将与提供的 value 一起提交。在 MDN 上阅读更多相关信息。

    ¥value?: string- Works only for inputs of type checkbox and radio. When a form is submitted, checkboxes and radios are submitted with the provided value. Read more about it on MDN.

FieldInputProps<Value>

一个对象包含:

¥An object that contains:

  • name: string - 字段名称

    ¥name: string - The name of the field

  • checked?: boolean - 无论是否检查输入,仅当 useField 传递带有 nametype: 'checkbox'type: 'radio' 的对象时才会定义。

    ¥checked?: boolean - Whether or not the input is checked, this is only defined if useField is passed an object with a name, type: 'checkbox' or type: 'radio'.

  • onBlur: () => void - 模糊事件处理程序

    ¥onBlur: () => void - A blur event handler

  • onChange: (e: React.ChangeEvent<any>) => void - 更改事件处理程序

    ¥onChange: (e: React.ChangeEvent<any>) => void - A change event handler

  • value: Value - 该字段的值(从 values 中提取),或者,如果它是复选框或单选输入,则可能将 value 传递到 useField

    ¥value: Value - The field's value (plucked out of values) or, if it is a checkbox or radio input, then potentially the value passed into useField.

  • multiple?: boolean - 是否可以选择多个值。仅当 useField 传递带有 multiple: true 的对象时才定义

    ¥multiple?: boolean - Whether or not the multiple values can be selected. This is only ever defined when useField is passed an object with multiple: true

FieldMetaProps<Value>

包含有关字段的相关计算元数据的对象。进一步来说,

¥An object that contains relevant computed metadata about a field. More specifically,

  • error?: string - 该字段的错误消息(从 errors 中摘取)

    ¥error?: string - The field's error message (plucked out of errors)

  • initialError?: string - 如果该字段存在于 initialErrors 中(从 initialErrors 中剔除),则该字段的初始错误

    ¥initialError?: string - The field's initial error if the field is present in initialErrors (plucked out of initialErrors)

  • initialTouched: boolean - 如果该字段存在于 initialTouched 中(从 initialTouched 中提取),则该字段的初始值

    ¥initialTouched: boolean - The field's initial value if the field is present in initialTouched (plucked out of initialTouched)

  • initialValue?: Value - 如果字段在 initialValues 中指定值(从 initialValues 中提取),则该字段的初始值

    ¥initialValue?: Value - The field's initial value if the field is given a value in initialValues (plucked out of initialValues)

  • touched: boolean - 该字段是否被访问过(从 touched 中抽取)

    ¥touched: boolean - Whether the field has been visited (plucked out of touched)

  • value: any - 该字段的值(从 values 中选取)

    ¥value: any - The field's value (plucked out of values)

FieldHelperProps

包含辅助函数的对象,你可以使用这些函数强制更改相关字段的值、错误值或触摸状态。这对于需要直接更改字段状态而不触发更改或模糊事件的组件非常有用。

¥An object that contains helper functions which you can use to imperatively change the value, error value or touched status for the field in question. This is useful for components which need to change a field's status directly, without triggering change or blur events.

  • setValue(value: any, shouldValidate?: boolean): Promise<void | FormikErrors> - 更改字段值的函数。如果 validateOnChange 设置为 true(默认情况下),调用此函数将触发验证运行。你还可以通过传递第二个参数作为 false 来显式阻止/跳过验证。如果 validateOnChange 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。

    ¥setValue(value: any, shouldValidate?: boolean): Promise<void | FormikErrors> - A function to change the field's value. Calling this will trigger validation to run if validateOnChange is set to true (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as false. If validateOnChange is set to true and there are errors, they will be resolved in the returned Promise.

  • setTouched(value: boolean, shouldValidate?: boolean): void - 更改字段触摸状态的函数。如果 validateOnBlur 设置为 true(默认情况下),调用此函数将触发验证运行。你还可以通过传递第二个参数作为 false 来显式阻止/跳过验证。如果 validateOnBlur 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。

    ¥setTouched(value: boolean, shouldValidate?: boolean): void - A function to change the field's touched status. Calling this will trigger validation to run if validateOnBlur is set to true (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as false. If validateOnBlur is set to true and there are errors, they will be resolved in the returned Promise.

  • setError(value: any): void - 更改字段错误值的函数

    ¥setError(value: any): void - A function to change the field's error value

Formik 中文网 - 粤ICP备13048890号