You need to enable JavaScript to run this app. 使用react-hook-form开发react-native登录页password始终报required错误怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

使用react-hook-form开发react-native登录页password始终报required错误怎么解决

问题原因

你代码里存在4个明确的错误点,共同导致了初始加载就触发密码必填校验的问题:

  1. 输入事件绑定错误:React Native 原生TextInput组件的onChange回调返回的是原生事件对象,而非用户输入的文本内容。你直接将Controller返回的onChange传给onChange属性,会导致表单无法正确获取字段值,误判字段为未定义的空状态触发必填校验。正确的用法是使用onChangeText属性绑定回调。
  2. 校验规则位置错误:用户名字段的rules属性写在了TextInput的属性上,只有写在<Controller>组件自身属性上的校验规则才会被react-hook-form识别生效。
  3. 默认值重复配置:你已经在useForm的入参中配置了全局defaultValues,不需要再在每个<Controller>上单独声明defaultValue="",重复配置可能会导致初始值覆盖异常。
  4. 渲染内日志导致的异常触发:你把console.log(errors)直接写在了JSX返回结构中,react-hook-form的formState是响应式Proxy对象,在渲染阶段直接访问errors会触发响应式依赖收集,甚至触发不必要的初始校验,同时每次组件重渲染都会执行该日志,输出的也可能是Proxy的快照而非实际的错误状态。

修复代码

import { useEffect } from 'react';
import { View, TextInput, Text, Button } from 'react-native';
import { useForm, Controller } from 'react-hook-form';

const Login = () => {
  const { control, handleSubmit, formState: { errors } } = useForm({
    mode: 'onSubmit', // 显式指定只有提交时才触发校验,默认也是该值,显式写更清晰
    defaultValues: {
      username: '',
      password: ''
    }
  });

  const onSubmit = (data) => {
    console.log(data)
  };

  // 需查看errors变化时用useEffect监听,不要放在渲染逻辑内
  useEffect(() => {
    console.log(errors);
  }, [errors]);
    
  return (
      <View>
        <Controller
          name="username" // 如果你确定fields.username是正确的字符串可以改回去,这里先写死排查字段名问题
          control={control}
          rules={{ required: { value: true, message: 'Username is required' } }} // rules移到Controller属性上
          render={({ onChange, value }) => (
          <TextInput
            onChangeText={onChange} // 替换成onChangeText
            value={value}
            placeholder='Username'
          />
          )}
        />
        {errors.username && <Text>UserName is required.</Text>}
        <Controller
          name="password" // 同理可替换回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
            onChangeText={onChange} // 替换成onChangeText
            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>}
        <Button title='Submit' onPress={handleSubmit(onSubmit)} />
      </View>
  )
}

export default Login;

内容的提问来源于stack exchange,提问作者TWOcvfan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 18:27:05