<ErrorMessage />

<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>
<Formik
initialValues={{
name: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
// same shape as initial values
console.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 狀態中欄位的的名稱。要訪問巢狀物件或陣列,名稱也可以接受 lodash 風格的點路徑,例如 social.facebookfriends[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>} />
這個頁面有幫助嗎?

訂閱我們的電子報

最新的 Formik 新聞、文章和資源,將會寄送到您的收件匣。

版權所有 © 2020 Formium, Inc. 保留所有權利。