如何为循环内的MUI TextField添加独立必填校验错误提示
解决Material-UI TextField遍历渲染时错误提示关联错误的问题
我使用Material-UI的TextField组件作为表单输入框,希望用户点击提交后,为空的必填字段显示红色错误边框。但当前需遍历数组渲染TextField,每个字段关联GET_TEXTFIELD中的字段ID(如M1、M2、M3),现出现问题:若某字段(如M1)为空,其他已填写的TextField(如M2、M3)也会触发错误提示,不符合预期。尝试error={errors.M1?.type === 'required'}会导致所有字段报错,请问该如何编写error属性的逻辑?
相关代码如下:
const { register, formState: { errors } } = useFormContext(); const GET_TEXTFIELD = { v1: 'M1', v2: 'M2', v3: 'M3' }; <Box display="flex"> {SOME_ARRAY.map((input) => ( <TextField {...register(GET_TEXTFIELD[input.fieldId], { required: true })} placeholder="Enter relevant additional information" fullWidth multiline error={// what should my logic be here?} /> ) </Box>
解决方案
核心是让每个TextField的error属性仅关联自身对应的字段错误,而非硬编码固定字段。具体实现如下:
修改后的完整代码
const { register, formState: { errors } } = useFormContext(); const GET_TEXTFIELD = { v1: 'M1', v2: 'M2', v3: 'M3' }; <Box display="flex"> {SOME_ARRAY.map((input) => { // 动态获取当前TextField对应的字段名 const fieldName = GET_TEXTFIELD[input.fieldId]; return ( <TextField {...register(fieldName, { required: true })} placeholder="Enter relevant additional information" fullWidth multiline // 仅判断当前字段的必填错误 error={!!errors[fieldName] && errors[fieldName].type === 'required'} /> ) })} </Box>
逻辑说明
- 动态绑定字段:通过
input.fieldId获取当前TextField对应的字段名,确保每个组件只关联自身的表单字段 - 精准错误判断:
!!errors[fieldName]先校验该字段是否存在错误对象,避免读取undefined属性报错errors[fieldName].type === 'required'精准匹配必填项错误类型,确保只有空必填字段才显示红色错误边框
内容的提问来源于stack exchange,提问作者user21476047
相关产品推荐
相关产品推荐

