React Native向函数传递输入值遇undefined问题求助
解决React Native输入框值传递后console.log显示undefined的问题
你的代码里有三个核心问题导致状态一直是undefined,直接按以下方式修改即可:
问题分析
- 状态未初始化:
useState()没有设置初始值,且未把userInfo里的默认值同步到状态中,初始状态就是undefined。 - onChangeText逻辑错误:两个输入框都没有使用输入的新值
newText更新状态,反而一直赋值固定的userInfo.user.name,完全没同步输入内容;邮箱输入框还错误地引用了name字段。 - 缺少可选链保护:如果
userInfo或log不存在,会直接抛出报错。
修复后的完整代码
import { useState } from 'react'; import { View, TextInput, Button, StyleSheet } from 'react-native'; export default function Signupfor(props) { // 解构路由参数,加默认空对象防止报错 const { userInfo, log } = props?.route?.params || {}; // 用userInfo的默认值初始化状态,处理undefined情况 const [name, setName] = useState(userInfo?.user?.name || ''); const [email, setEmail] = useState(userInfo?.user?.email || ''); function getAlldata() { console.log(name, email); } console.log(log?.name); return ( <View style={styles.prheight}> <View style={styles.form}> <TextInput onChangeText={(newText) => setName(newText)} style={styles.input} label="Name" value={name} /> <TextInput style={styles.input} label="Email" onChangeText={(newText) => setEmail(newText)} value={email} /> <View style={styles.button}> <Button title="Lets Go" onPress={getAlldata} /> </View> </View> </View> ); } // 补充原代码缺失的样式定义 const styles = StyleSheet.create({ prheight: { flex: 1, padding: 20, }, form: { gap: 15, }, input: { height: 50, borderWidth: 1, borderColor: '#ccc', paddingHorizontal: 10, borderRadius: 8, }, button: { marginTop: 20, }, });
关键修改说明
- 状态初始化:直接用
userInfo里的默认值初始化useState,并通过|| ''确保初始值为字符串类型,避免undefined。 - 受控组件绑定:把
defaultValue改为value,绑定对应状态,让输入框内容和状态完全同步,解决默认值仅初始化一次的问题。 - 修正onChangeText:使用输入的
newText参数更新状态,确保输入内容能同步到name和email状态中。 - 增加健壮性:用可选链
?.和默认空对象处理可能的undefined参数,避免运行时报错。
内容的提问来源于stack exchange,提问作者vivek kn
相关产品推荐
相关产品推荐

