跨组件实现Material-UI TextField提交后错误红框高亮
解决方案
你可以借助React Hook Form的FormContext来跨组件共享表单状态(包括错误信息),这样就能在QuestionOneComponent中获取到提交后的错误,进而给TextField设置error属性。具体步骤如下:
1. 在根表单组件中配置FormProvider
在包含ActionsComponent和QuestionOneComponent的父组件里,用FormProvider包裹子组件,传入React Hook Form的表单实例:
import { FormProvider, useForm } from 'react-hook-form'; export default function ParentFormComponent() { const formMethods = useForm({ // 可添加表单配置,比如defaultValues等 }); return ( <FormProvider {...formMethods}> <QuestionOneComponent /> <ActionsComponent /> </FormProvider> ); }
2. 修改ActionsComponent,通过上下文获取表单方法
无需在组件内单独定义handleSubmit,直接从FormContext中获取:
import { useFormContext } from 'react-hook-form'; import { FieldErrors } from 'react-hook-form'; export default function ActionsComponent() { const { handleSubmit } = useFormContext(); const showErrors = (errors: FieldErrors) => { const { id } = showModal(SimpleStatusDialog, { title: '必填字段为空!', content: ( <Box display="flex" flexDirection="column" className={cl.boxSpacing}> {Object.entries(errors).map(([fieldId, errorProps]) => ( <Box display="flex" className={cl.boxSpacing} key={fieldId}> <Typography>{`${fieldId}:`}</Typography> <Typography type="negative"> {errorProps?.message || errorProps?.root?.message || '此字段为必填项'} </Typography> </Box> ))} </Box> ), closeFn: () => hideModal(id), }); }; const submitQuestions = (data: any) => { // 此处编写你的提交逻辑 }; return ( <Box display="flex" justifyContent="space-between" p={2} className={cl.stickyButtons}> <Box display="flex" className={cl.boxSpacing}> <Button sdsButtonType="primary" onClick={handleSubmit(submitQuestions, showErrors)}> 提交 </Button> </Box> </Box> ); }
3. 修改QuestionOneComponent,绑定错误状态到TextField
从FormContext中获取register和errors,给TextField添加error属性:
import { useFormContext } from 'react-hook-form'; export default function QuestionOneComponent() { const { register, formState: { errors } } = useFormContext(); return ( <> <Typography type="negative">请在此处提供任何额外细节</Typography> <TextField {...register('M1', { required: '此字段为必填项' })} placeholder="输入相关附加信息" fullWidth multiline error={!!errors.M1} helperText={errors.M1?.message} {/* 可选:显示错误提示文字 */} /> </> ); }
关键说明
- React Hook Form的
FormProvider会将表单实例传递给所有子组件,实现跨组件访问errors、register等核心方法。 - 提交失败后
errors对象会自动更新,TextField的error属性会根据errors.M1的存在状态切换红色边框样式,模态框关闭后该状态会保留,空字段会自动高亮红框。
内容的提问来源于stack exchange,提问作者user21476047
相关产品推荐
相关产品推荐

