如何在Formik字段组件中显示自定义<ErrorMessage>并禁用默认错误提示
解决Formik + formik-material-ui错误提示重复显示的问题
你遇到的重复错误提示,核心原因是**formik-material-ui提供的TextField组件会自动从Formik的上下文里读取错误信息,并把它作为helperText显示出来**,而你又手动添加了ErrorMessage组件,两者叠加就导致了重复提示。
要禁用默认的错误提示,只需要在自定义TextField组件中覆盖默认的helperText,同时按需保留输入框的错误样式(比如红色边框),下面是两种可行的修改方案:
方案一:使用useFormikContext控制状态
通过Formik的useFormikContext钩子获取表单的touched和errors状态,手动控制TextField的错误样式,同时清空默认的helperText:
import React, { Fragment } from "react"; import { Field, ErrorMessage, useFormikContext } from "formik"; import { TextField } from "libs/formik-material-ui/src"; const TextFieldStyle = { padding: 8, fontSize: "0.75rem", }; export default React.memo((props: any) => { // 获取Formik的表单状态 const { touched, errors } = useFormikContext(); // 判断当前字段是否已触碰且有错误 const hasError = touched[props.name] && !!errors[props.name]; return ( <Fragment> <Field component={TextField} inputProps={{ style: TextFieldStyle }} size="small" margin="none" variant="outlined" helperText="" // 清空默认错误提示文本 error={hasError} // 保留输入框的错误边框样式 {...props} // 允许外部props覆盖内部配置 > {props.children} </Field> <ErrorMessage name={props.name}> {(msg) => <div style={{ color: "red", textAlign: "left" }}>{msg}</div>} </ErrorMessage> </Fragment> ); });
方案二:使用Field的render函数(更灵活)
改用Field的render prop来渲染TextField,这样可以直接拿到当前字段的状态,更精细地控制组件属性:
import React, { Fragment } from "react"; import { Field, ErrorMessage } from "formik"; import { TextField } from "libs/formik-material-ui/src"; const TextFieldStyle = { padding: 8, fontSize: "0.75rem", }; export default React.memo((props: any) => { return ( <Fragment> <Field name={props.name}> {({ field, form }) => { const { touched, errors } = form; const hasError = touched[field.name] && !!errors[field.name]; return ( <TextField {...field} {...props} inputProps={{ style: TextFieldStyle }} size="small" margin="none" variant="outlined" helperText="" // 禁用默认错误提示 error={hasError} // 保留错误样式 /> ); }} </Field> <ErrorMessage name={props.name}> {(msg) => <div style={{ color: "red", textAlign: "left" }}>{msg}</div>} </ErrorMessage> </Fragment> ); });
关键说明
- 设置
helperText=""是核心:这会覆盖formik-material-ui自动生成的错误提示文本,避免重复显示。 - 保留
error={hasError}:让输入框在字段触碰且有错误时显示红色边框,保持用户友好的视觉提示;如果你不需要这个样式,直接设置error={false}即可。
内容的提问来源于stack exchange,提问作者Harsh Agarwal
相关产品推荐
相关产品推荐

