</> ErrorMessage:
Component
一个简单的组件,用于渲染关联输入的错误消息。
¥A simple component to render associated input's error message.
npm install @hookform/error-message
属性
¥Props
名称 | 类型 | 必需的 | 描述 |
---|---|---|---|
name | string | ✓ | 字段名称。 |
errors | object | React Hook Form 中的 errors 对象。如果你使用的是 FormProvider ,则可选。 | |
message | string | React.ReactElement | 内联错误消息。 | |
as | React.ElementType | string | 封装组件或 HTML 标签。例如:as="span" 或 as={<Text />} | |
render | ({ message: string | React.ReactElement, messages?: Object}) => any | 这是一个 渲染属性,用于渲染错误消息或消息。 注意:你需要将 criteriaMode 设置为 'all' 才能使用 messages 。 |
示例:
¥Examples:
单个错误消息
¥Single Error Message
import React from "react"import { useForm } from "react-hook-form"import { ErrorMessage } from "@hookform/error-message"interface FormInputs {singleErrorInput: string}export default function App() {const {register,formState: { errors },handleSubmit,} = useForm<FormInputs>()const onSubmit = (data: FormInputs) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><input{...register("singleErrorInput", { required: "This is required." })}/><ErrorMessage errors={errors} name="singleErrorInput" /><ErrorMessageerrors={errors}name="singleErrorInput"render={({ message }) => <p>{message}</p>}/><input type="submit" /></form>)}
多个错误消息
¥Multiple Error Messages
import React from "react"import { useForm } from "react-hook-form"import { ErrorMessage } from "@hookform/error-message"interface FormInputs {multipleErrorInput: string}export default function App() {const {register,formState: { errors },handleSubmit,} = useForm<FormInputs>({criteriaMode: "all",})const onSubmit = (data: FormInputs) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><input{...register("multipleErrorInput", {required: "This is required.",pattern: {value: /d+/,message: "This input is number only.",},maxLength: {value: 10,message: "This input exceed maxLength.",},})}/><ErrorMessageerrors={errors}name="multipleErrorInput"render={({ messages }) =>messages &&Object.entries(messages).map(([type, message]) => (<p key={type}>{message}</p>))}/><input type="submit" /></form>)}