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

React Native中TextInput组件onSubmitEditing返回undefined问题求助

解决React Native TextInput onSubmitEditing输出undefined的问题

问题原因

onSubmitEditing的回调参数是事件对象,而非直接的输入文本。如果你的txtHandler1直接尝试将参数当作文本打印或使用,就会出现undefined,或是拿到事件对象而非预期的输入内容。

解决方案

方案1:从事件对象中提取输入文本

修改处理函数,通过event.nativeEvent.text获取输入框的实际内容:

const txtHandler1 = (event) => {
  const inputText = event.nativeEvent.text;
  console.log(inputText); // 正常输出输入的文本
};

// 组件代码保持不变
<View>
  <Text>Name of Industry </Text>
  <TextInput
    placeholder='Your Answer'
    onSubmitEditing={txtHandler1}
  />
</View>

方案2:使用受控组件(推荐)

通过useState维护输入框状态,结合onChangeText实时更新状态,onSubmitEditing直接读取状态值:

import { useState } from 'react';
import { View, Text, TextInput } from 'react-native';

// 定义状态
const [industryName, setIndustryName] = useState('');

const txtHandler1 = () => {
  console.log(industryName); // 直接读取状态中的文本内容
};

// 组件部分
<View>
  <Text>Name of Industry </Text>
  <TextInput
    placeholder='Your Answer'
    value={industryName}
    onChangeText={setIndustryName}
    onSubmitEditing={txtHandler1}
  />
</View>

额外注意事项

  • iOS设备需确认键盘的提交按钮(如“完成”“回车”)可正常触发回调;Android设备同理检查键盘提交按钮配置。
  • 若输入框设置了multiline={true},onSubmitEditing可能不会触发(多行输入时回车会换行),这种场景建议添加独立的提交按钮。

内容的提问来源于stack exchange,提问作者Sandeep Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:55:19