Mui 风格的组件未使用 React-hook-form 注册

问题描述 投票:0回答:1

如果我注册用户名和密码时没有使用 mui 风格的组件。它有效

//This works fine
        <TextField
          id="username"
          type="text"
          autoComplete="off"
          inputProps={{ 'data-testid': 'username' }}
          label={t('COMMON.USERNAME')}
          helperText={errors.username && t('LOGIN_PAGE.THIS_FIELD_IS_REQUIRED')}
          sx={{ width: '100%' }}
          {...register('username', { required: true })}
          error={!!errors.username || isLoginError}
        />
        <TextField
          id="password"
          type="password"
          autoComplete="off"
          inputProps={{ 'data-testid': 'password' }}
          label={t('COMMON.PASSWORD')}
          helperText={errors.password && t('LOGIN_PAGE.THIS_FIELD_IS_REQUIRED')}
          sx={{ width: '100%' }}
          {...register('password', { required: true })}
          error={!!errors.password || isLoginError}
        />

如果我尝试创建一个 mui 风格的组件并将 props 传递给它,这不会通过react-hook-form注册

//username component is not registered with react-hook-form

//create styled component out of react component like this
  const StyledTextField = styled((props: TextFieldProps) => (
    <TextField
      id="username"
      type="text"
      autoComplete="off"
      inputProps={{ 'data-testid': 'username' }}
      sx={{ width: '100%' }}
      {...props}
    />
  ))();


// using it like this,
        <StyledTextField
          label={t('COMMON.USERNAME')}
          helperText={errors.username && t('LOGIN_PAGE.THIS_FIELD_IS_REQUIRED')}
          {...register('username', { required: true })}
          error={!!errors.username || isLoginError}
        />
        <TextField
          id="password"
          type="password"
          autoComplete="off"
          inputProps={{ 'data-testid': 'password' }}
          label={t('COMMON.PASSWORD')}
          helperText={errors.password && t('LOGIN_PAGE.THIS_FIELD_IS_REQUIRED')}
          sx={{ width: '100%' }}
          {...register('password', { required: true })}
          error={!!errors.password || isLoginError}
        />

不知道我在这里做错了什么......

material-ui styled-components react-hook-form emotion
1个回答
0
投票

我认为这是因为您的样式组件没有转发引用,如果您检查

register
函数的返回值,您会注意到对输入的引用。 https://react-hook-form.com/docs/useform/register

register: (name: string, RegisterOptions?) => ({ onChange, onBlur, name, ref })

在样式组件中转发引用,或者使用正确的样式语法。如果你使用 Mui 风格,正确的语法应该是这样的:

const StyledTextField = styled(TextField)({
 //css here
});
© www.soinside.com 2019 - 2024. All rights reserved.