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

React Native无法从state获取TextInput输入值问题咨询

问题原因

你代码存在两个核心问题,其中直接导致打印出大段事件对象的原因是:

  • TextInput事件属性使用错误:你当前使用的onChange事件回调的入参是React Native封装的原生合成事件对象(也就是你控制台看到的SyntheticEvent内容),并非输入框的文本内容,你直接将整个事件对象存入了task状态,自然无法获取到正确的输入文本。
  • 附带拼写错误:KeyboardAvoidingView的键盘避让属性正确名称是behavior(美式拼写),你写的behaviour是英式拼写,会导致键盘避让逻辑完全失效。
修复方案
  1. 将TextInput的onChange替换为onChangeText,该事件的回调入参直接就是输入框的文本字符串,不需要额外从事件对象里取值:
<TextInput 
  style={styles.tastText} 
  placeholder={'Write a Task'} 
  value={task} 
  onChangeText={text => setTask(text)}
/>
  1. 给useState添加空字符串初始值,避免初始值为undefined产生的非受控组件警告:
const [task, setTask] = useState('');
  1. 修正KeyboardAvoidingView的属性拼写错误:
<KeyboardAvoidingView 
  style={styles.bottomBar}
  behavior={Platform.OS === 'ios' ? 'padding' : 'height'} 
>

可选优化:Task组件接收props时可以直接解构参数,不需要自定义props名再取属性,写法更简洁:

const Task = ({text}) => {
  return (
    <View style={styles.container}>
      <View style ={styles.styleleft}>
      <View style ={styles.square}></View>
      <Text>{text}</Text>
      </View>
      <View style ={styles.styleright}></View>
    </View>
  )
}

内容的提问来源于stack exchange,提问作者John George

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:03:05