<ErrorMessage />
是一个组件,如果给定字段已被访问(即 touched[name] === true
)(并且存在 error
消息),则会渲染该字段的错误消息。它期望所有错误消息都作为字符串存储在给定字段中。与 <Field />
、<FastField />
和 <FieldArray />
一样,支持类似 lodash 的点路径和括号语法。
import React from 'react';import { Formik, Form, Field, ErrorMessage } from 'formik';import * as Yup from "yup";const SignupSchema = Yup.object().shape({name: Yup.string().min(2, 'Too Short!').max(70, 'Too Long!').required('Required'),email: Yup.string().email('Invalid email').required('Required'),});export const ValidationSchemaExample = () => (<div><h1>Signup</h1><FormikinitialValues={{name: '',email: '',}}validationSchema={SignupSchema}onSubmit={values => {// same shape as initial valuesconsole.log(values);}}>{({ errors, touched }) => (<Form><Field name="name" />- {errors.name && touched.name ? (- <div>{errors.name}</div>- ) : null}+ <ErrorMessage name="name" /><Field name="email" type="email" />- {errors.email && touched.email ? (- <div>{errors.email}</div>- ) : null}+ <ErrorMessage name="email" /><button type="submit">Submit</button></Form>)}</Formik></div>);
children
children?: ((message: string) => React.ReactNode)
返回有效 React 元素的函数。仅当字段已被触碰且存在错误时才会调用。
// the render callback will only be called when the// field has been touched and an error exists and subsequent updates.<ErrorMessage name="email">{msg => <div>{msg}</div>}</ErrorMessage>
component
component?: string | React.ComponentType<FieldProps>
要渲染的 React 组件或 HTML 元素的名称。如果未指定,<ErrorMessage>
将只返回一个字符串。
<ErrorMessage component="div" name="email" />// --> {touched.email && error.email ? <div>{error.email}</div> : null}<ErrorMessage component="span" name="email" />// --> {touched.email && error.email ? <span>{error.email}</span> : null}<ErrorMessage component={Custom} name="email" />// --> {touched.email && error.email ? <Custom>{error.email}</Custom> : null}<ErrorMessage name="email" />// This will return a string. React 16+.// --> {touched.email && error.email ? error.email : null}
id
id?: string
Formik 状态中字段的 id。为了访问用于端到端测试目的的 DOM 元素,它不会以任何方式影响实现,因为仍然可以省略该属性。
// id will be used only for testing purposes// not contributing anything to the core implementation.<ErrorMessage name="email" id="form_email_id" />
name
name: string
必填
Formik 状态中字段的名称。要访问嵌套对象或数组,name 也可以接受类似 lodash 的点路径,例如 social.facebook
或 friends[0].firstName
render
render?: (error: string) => React.ReactNode
返回有效 React 元素的函数。仅当字段已被触碰且存在错误时才会调用。
// the render callback will only be called when the// field has been touched and an error exists and subsequent updates.<ErrorMessage name="email" render={msg => <div>{msg}</div>} />