React Native中用函数提交表单,useEffect调用react-hook-form的handleSubmit失效如何解决?
问题根因与修复方案
你的代码存在3个核心逻辑错误,导致自动提交不生效:
- 调用
handleSubmit的方式不符合react-hook-form的API规范:handleSubmit是高阶函数,接收提交回调作为入参,执行后返回的函数才是实际触发提交的方法,你需要主动调用这个返回值 - 表单实例不统一:当前组件接收父级传入的
control,说明表单实例在父级创建,子组件内单独调用useForm拿到的handleSubmit和父级表单无关,无法操作父级表单数据 - 冗余的本地字段状态:不需要单独维护
field存储输入值,直接监听表单字段即可,避免值不同步问题
修复后代码
import React, {useRef} from 'react'; import {View, Text, TextInput} from 'react-native'; import tailwind from 'tailwind-rn'; import {useDebounce} from 'use-debounce'; import {Controller, useWatch} from 'react-hook-form'; import {MAIN_COLOR, GRAY} from '../../constants/theme'; function RegisterFormHook({data, onSubmit, control, errors, handleSubmit}) { const [underlineColor, setUnderlineColor] = React.useState(GRAY); const inputElement = useRef(); // 直接监听当前表单字段的值,不需要单独维护本地状态 const fieldValue = useWatch({ control, name: data.name, defaultValue: '' }); // 对表单字段值做防抖 const [debouncedValue] = useDebounce(fieldValue, 1000); React.useEffect(() => { if (debouncedValue.trim().length === 0) return; // 正确调用handleSubmit:先传提交回调,再执行返回的提交函数 handleSubmit((formData) => onSubmit(formData))(); }, [debouncedValue, handleSubmit, onSubmit]); const onFocus = () => { setUnderlineColor(MAIN_COLOR); }; const onBlur = () => { setUnderlineColor(GRAY); }; return ( <View style={tailwind('px-8')}> <Controller control={control} name={data.name} rules={data.rules} render={({field: {onChange, value}}) => ( <TextInput placeholder={data.placeholder} ref={inputElement} style={[ tailwind('text-black p-0 text-xl pb-1 flex-row'), { borderBottomWidth: 1, borderBottomColor: underlineColor, }, ]} onChangeText={onChange} onBlur={onBlur} value={value} onFocus={onFocus} /> )} /> <Text style={{color: 'red'}}>{errors[data.name]?.message}</Text> </View> ); } export default RegisterFormHook;
父组件适配
你需要在父级调用useForm的地方,把返回的handleSubmit作为属性传给当前组件,示例如下:
// 父组件内的useForm调用 const {control, handleSubmit, formState: {errors}} = useForm({ // 你的表单配置 }); // 渲染子组件时传递handleSubmit <RegisterFormHook data={你的字段配置} onSubmit={你的提交逻辑} control={control} errors={errors} handleSubmit={handleSubmit} // 新增传递这个属性 />
内容的提问来源于stack exchange,提问作者Alvaro
相关产品推荐
相关产品推荐

