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

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,
  },
});

关键修改说明

  1. 状态初始化:直接用userInfo里的默认值初始化useState,并通过|| ''确保初始值为字符串类型,避免undefined。
  2. 受控组件绑定:把defaultValue改为value,绑定对应状态,让输入框内容和状态完全同步,解决默认值仅初始化一次的问题。
  3. 修正onChangeText:使用输入的newText参数更新状态,确保输入内容能同步到name和email状态中。
  4. 增加健壮性:用可选链?.和默认空对象处理可能的undefined参数,避免运行时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:20:44