React Native中使用<form>标签触发Invariant Violation错误的问题求助
React Native中使用
你好!我之前碰到过一模一样的问题,其实根源很简单:React Native里根本没有原生的<form>标签,你代码里用到的是Web端HTML的<form>,RN无法识别这个组件,所以才抛出了这个"Invariant Violation"错误。
错误原因解析
错误提示里的"View config getter callback for component must be a function",本质就是RN找不到<form>对应的原生组件配置——它是HTML标签,不是RN内置的组件(RN的核心组件是View、Text、TextInput这类),自然会返回undefined,触发报错。
解决方案
我们只需要移除Web端的<form>标签,然后调整提交逻辑即可,同时顺便修复代码里的小问题:
- 删除
<form>包裹标签:RN不需要用form来管理表单,react-hook-form的handleSubmit可以直接绑定到触发提交的组件上 - 调整提交触发方式:把
handleSubmit(onSubmit)绑定到TouchableOpacity的onPress事件上(RN的TouchableOpacity不支持Web的type="submit"属性) - 修复变量声明问题:你的
navigation和dispatch没有用const声明,这会导致语法问题,需要补上
下面是修改后的完整代码:
import React from "react"; import {Image, ImageBackground, TouchableOpacity, View, ScrollView, Text, StyleSheet, Alert} from "react-native"; import { useDispatch, useSelector } from "react-redux"; import { useNavigation } from "@react-navigation/native"; import styled from "styled-components"; import {useForm} from "react-hook-form" import { accountStatus, fetchAccount } from "../redux/slices/account"; export default function Log_in(){ // 补上const声明 const navigation = useNavigation() const isAuth = useSelector(accountStatus) const dispatch = useDispatch() const {register, handleSubmit, setError, formState: {errors, isValid}} = useForm({ defaultValues:{ email: '', password: '' }, mode: "onChange" }) const onSubmit = (values) => { dispatch(fetchAccount(values)) } if(isAuth) { navigation.navigate("LogedIn") } // 移除<form>标签,直接返回RN组件结构 return( <Center> <Log_Text>Войдите в аккаунт</Log_Text> <Input placeholder="Введите e-mail" {...register('email', {required: "Укажите почту"})} /> <Input placeholder="Введите пароль" {...register('password', {required: "Укажите пароль"})} /> {/* 把handleSubmit绑定到onPress,移除无效的type="submit" */} <TouchableOpacity onPress={handleSubmit(onSubmit)}> <ImageBackground source={require('../assets/img-profile/place_an_order_2.png')} imageStyle={{borderRadius: 10}} style={{marginTop: 14, width: "auto", height: 40}}> <Text style={{ color: '#fff', fontSize: 18, fontWeight: '600', textAlign: 'center', marginTop: 6 }}> Войти </Text> </ImageBackground> </TouchableOpacity> </Center> ); } const Input = styled.TextInput` margin: 10px 20px 0 20px; padding: 6px 0 6px 14px; width: 300px; color: #000000; border-width: 1.5px; border-radius: 15px; border-color:#B6D3FF; background-color: #fff `; const Center = styled.View` margin-left: auto; margin-right: auto; margin-top:80%; `; const Log_Text = styled.Text` font-size: 20px; font-weight: 600; `;
额外说明
React Native的组件体系和Web完全不同,不要混用HTML标签。表单的提交逻辑,只需要通过RN的触摸交互组件(比如TouchableOpacity、Button)的onPress事件,直接触发react-hook-form的handleSubmit就可以完成,和Web端的表单提交逻辑是不一样的。
备注:内容来源于stack exchange,提问作者ParoVchiK
相关产品推荐
相关产品推荐

