MUI Styled组件无法与React-Hook-Form注册问题求助
问题原因及解决方案
问题出在StyledTextField没有正确转发ref到内部MUI TextField组件——React Hook Form的register方法依赖ref来注册并跟踪表单字段,缺失ref转发会导致username字段无法被表单识别。
修复代码
修改StyledTextField的定义,通过React.forwardRef把ref转发到内部TextField,同时确保所有props(包括register返回的属性)正确传递:
import React from 'react'; import { styled, TextField, TextFieldProps } from '@mui/material'; const StyledTextField = styled( React.forwardRef<HTMLInputElement, TextFieldProps>((props, ref) => ( <TextField ref={ref} id="username" type="text" autoComplete="off" inputProps={{ 'data-testid': 'username' }} sx={{ width: '100%' }} {...props} /> )) )();
如果需要复用这个StyledTextField到其他字段(比如密码),建议不要硬编码id、type等属性,改为外部传递:
const StyledTextField = styled( React.forwardRef<HTMLInputElement, TextFieldProps>((props, ref) => ( <TextField ref={ref} autoComplete="off" sx={{ width: '100%' }} {...props} /> )) )(); // 使用时传递专属属性 <StyledTextField id="username" type="text" inputProps={{ 'data-testid': 'username' }} label={t('COMMON.USERNAME')} helperText={errors.username && t('LOGIN_PAGE.THIS_FIELD_IS_REQUIRED')} {...register('username', { required: true })} error={!!errors.username || isLoginError} />
原理说明
register方法会生成一个ref,需要绑定到实际的input元素上才能完成字段注册。你之前的代码没有转发ref,导致这个ref无法到达内部TextField的input元素,React Hook Form无法跟踪该字段的状态和值,最终出现注册失败的问题。
内容的提问来源于stack exchange,提问作者Ankur Marwaha
相关产品推荐
相关产品推荐

