密码错误总是真的 react-hook-form

时间:2021-05-13 04:39:45

标签: react-native react-hook-form

我正在尝试使用 react-hook-form 以 react-native 进行登录,但是当我进入登录屏幕时,console.log(errors) 会显示这一行 password: {type: "required", message: "Password is required", ref: {…}}

我不明白为什么。

这是我的代码:

const Login = () => {
  const { control, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      username: '',
      password: ''
    }
  });

  const onSubmit = (data) => {
    console.log(data)
  }
    
  return (
      <View>
        <Controller
          defaultValue=""
          name={fields.username}
          control={control}
          render={({ onChange, value }) => (
          <TextInput
            onChange={onChange}
            value={value}
            placeholder='Username'
            rules={{ required: { value: true, message: 'Username is required' } }}
          />
          )}
        />
        {errors.username && <Text>UserName is required.</Text>}
        <Controller
          defaultValue=""
          name={fields.password}
          control={control}
          rules={{
            required: { value: true, message: 'Password is required' },
            minLength: {
              message: 'Use at least 4 characters.',
              value: 4,               
            },
          }}
          render={({ onChange, value }) => (
          <TextInput
            onChange={onChange}
            value={value}
            secureTextEntry={true}
            placeholder='Password'
          />
          )}
        />
        {errors.password?.type === "required" && <Text>Password is required.</Text>}
        
        {errors.password?.type === "minLength" && <Text>Minimum 4 characters are required</Text>}
        {console.log(errors)}
        <Button title='Submit' onPress={handleSubmit(onSubmit)} />
      </View>
  )
}

export default Login;

我不确定是不是错误,我希望有人能帮忙

1 个答案:

答案 0 :(得分:0)

您必须使用 onChangeText 道具而不是 onChange 来接收当前键入的输入值。

另一个小注意事项: 第一个 <Controller /> 错过了 rules,因为您将它作为 <TextInput /> 的道具放置。我在 CodeSandbox 中更正了它。

Edit RHF - React Native