React Native中使用react-hook-form Controller组件报TypeError求助
问题描述
在React Native应用中,将react-hook-form的Controller组件封装到独立的CustomInput组件后,登录页面调用该组件时出现以下错误:
TypeError: undefined is not an object (evaluating 'e.substring')
CustomInput.js 代码
import { View, TextInput, StyleSheet } from 'react-native' import React from 'react' import { Controller } from 'react-hook-form'; const CustomInput = ({control, name, placeholder, secureTextEntry}) => { return ( <View style={styles.container}> <Controller control={control} name={name} render={({field: {value, onChange, onBlur}, fieldState: {error}}) => <TextInput style={styles.input} value={value} onChangeText={onChange} onBlur={onBlur} placeholder={placeholder} secureTextEntry={secureTextEntry} /> } /> </View> ); };
LoginScreen.js 代码
import CustomInput from '../../components/CustomInput/CustomInput'; import { useNavigation } from '@react-navigation/native'; import {useForm} from 'react-hook-form'; const LoginScreen = () => { const {control, handleSubmit, formState: { errors } } = useForm(); const navigation = useNavigation(); const onLoginPressed = (data) => { console.log(data, errors) }; const onForgotPasswordPressed = () => { navigation.navigate('ForgotPassword'); } const onRegisterPressed = () => { navigation.navigate('Register') } return ( <ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }} showsVerticalScrollIndicator={false}> <View style={styles.root}> <Image source={Logo} style={[styles.logo, {height : height * 0.2}]} resizeMode={'contain'} /> //CUSTOM INPUT HOLDING THE CONTROLLER <CustomInput name='username' placeholder='Username' control={control} /> <CustomInput password='password' placeholder='Password' secureTextEntry={true} control={control}/> <CustomButton text={loading ? 'Loading...' : 'Login Account'} onPress={handleSubmit(onLoginPressed)} /> </View> </ScrollView> ); };
直接在登录页面使用Controller组件可正常运行,需解决封装后的错误。
解决方法
错误的核心原因是登录页面中密码输入框的传参错误:
CustomInput组件接收的字段是name,但调用密码输入框时传了password='password',导致Controller的name参数为undefined,触发了react-hook-form内部对字符串操作的错误(即报错中的e.substring)。
步骤1:修正传参
修改LoginScreen中密码输入框的代码,将password='password'改为name='password':
<CustomInput name='password' placeholder='Password' secureTextEntry={true} control={control}/>
额外优化建议
为避免TextInput初始渲染时因value为undefined出现警告,可在CustomInput的TextInput中给value设置默认空字符串:
<TextInput style={styles.input} value={value || ''} {/* 新增默认值 */} onChangeText={onChange} onBlur={onBlur} placeholder={placeholder} secureTextEntry={secureTextEntry} />
内容的提问来源于stack exchange,提问作者Imran Irshad
相关产品推荐
相关产品推荐

