You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用react-hook-form实现TextInput为空时显示错误提示

React Native + @react-hook-form 登录页必填校验不生效问题解决

核心问题分析

你的代码已配置required规则和错误提示,但未生效主要源于两个关键点:

  1. 缺少校验触发时机(默认仅调用handleSubmit时才会触发校验)
  2. 未传递onBlur事件,无法触发实时校验逻辑

修正方案

以下是完整可运行的优化代码:

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

export default function LoginScreen() {
  // 初始化useForm,设置失去焦点时触发校验
  const { control, errors, handleSubmit } = useForm({
    mode: 'onBlur',
  });

  const handleChangeText = (text, type) => {
    // 你的自定义文本处理逻辑
  };

  const onSubmit = (formData) => {
    // 登录提交逻辑
    console.log('提交的数据:', formData);
  };

  return (
    <View style={{ padding: 20, marginTop: 50 }}>
      <Controller
        control={control}
        name="username"
        defaultValue=""
        rules={{
          required: { value: true, message: "Nom d'utilisateur nécessaire" },
        }}
        render={({ field: { onChange, value, onBlur } }) => (
          <View>
            <TextInput
              value={value}
              placeholder={'utilisateur'}
              autoFocus={true}
              style={{
                borderWidth: 1,
                borderColor: '#ccc',
                borderRadius: 4,
                padding: 10,
                marginBottom: 4,
              }}
              onChangeText={(text) => {
                onChange(text);
                handleChangeText(text, 'login');
              }}
              onBlur={onBlur} // 必须传递此事件,才能触发onBlur模式的校验
              onSubmitEditing={() => { /* 密码框焦点切换逻辑 */ }}
            />
            {/* 错误提示组件,添加样式增强可读性 */}
            {errors.username && (
              <Text style={{ color: 'red', fontSize: 12 }}>
                {errors.username.message}
              </Text>
            )}
          </View>
        )}
      />

      {/* 密码输入框可复用同样逻辑 */}
      {/* <Controller ... /> */}

      <Button 
        title="Se connecter" 
        onPress={handleSubmit(onSubmit)} 
        style={{ marginTop: 20 }} 
      />
    </View>
  );
}

关键优化点说明

  • 设置校验模式:通过useForm({ mode: 'onBlur' })指定输入框失去焦点时自动触发校验,无需等待提交操作
  • 传递onBlur事件:必须将Controller提供的onBlur绑定到TextInput上,否则校验逻辑无法被触发
  • 错误提示样式:给错误文本添加红色样式,提升用户辨识度
  • 提交时统一校验:使用handleSubmit包裹提交函数,即使用户直接点击提交,也会触发所有字段的校验并显示错误

其他可选配置

如果需要实时校验(每输入一个字符就检查),可将mode改为onChange;若仅需提交时校验,保持默认mode: 'onSubmit'即可,此时错误提示仅在点击提交按钮后显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:32:45