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

Expo RN项目报错undefined is not an object,TextInput无法正常工作

解决React Native函数组件中使用this.state导致的"undefined is not an object"错误

嘿,刚接触React Native + Expo遇到这个问题很正常,咱们一步步拆解问题、解决它:

一、问题核心原因

你写的HomeScreen是函数组件(export default function HomeScreen()),但this.state和this.setState是类组件专属的状态管理语法。函数组件内部不存在指向组件实例的this,直接调用this会得到undefined,这就是你看到"undefined is not an object"错误的根源。

二、解决方法:改用useState钩子

函数组件的状态管理需要用React提供的useState钩子,这是函数组件的标准状态方案:

  1. 先在文件顶部导入useState:
import { useState } from 'react';
  1. 在函数组件内部替换this.state = {text: ''}为:
const [text, setText] = useState('');

这里text是存储输入内容的状态变量,setText是专门用来更新这个状态的函数。
3. 把代码里所有this.setState({text})改成setText(text),所有this.state.text直接换成text即可。

三、代码里的其他问题和修正

除了状态管理的问题,你的代码还有两个小细节需要调整:

  • TextInput属性拼写错误:placeHolder应该是placeholder(小写h),否则占位符文本不会显示。
  • Button的onPress写法错误:你现在直接写Alert.alert("Button pressed!"),会导致组件一渲染就触发弹窗,而不是点击按钮时触发。需要用箭头函数包裹,改成onPress={() => Alert.alert("Button pressed!")}。

四、修正后的完整代码

import React, { useState } from 'react';
import { View, ScrollView, TextInput, Button, Text, Alert, StyleSheet } from 'react-native';

export default function HomeScreen() { 
  // 用useState替代类组件的this.state
  const [text, setText] = useState(''); 

  return ( 
    <View style={styles.container}> 
      <ScrollView style={styles.scrollViewContainer} contentContainerStyle={styles.contentContainer}> 
        <View style={styles.searchContainer}> 
          {/* 修正placeholder拼写,替换this相关的状态调用 */}
          <TextInput 
            placeholder="Type something!" 
            onChangeText={(inputText) => setText(inputText)} 
            value={text} 
          /> 
        </View> 
        <View> 
          {/* 修正onPress的写法,用箭头函数包裹 */}
          <Button onPress={() => Alert.alert("Button pressed!")} title="Search" /> 
        </View> 
        <View style={styles.listContainer}> 
          {/* 直接使用状态变量text */}
          <Text>{text}</Text> 
        </View> 
      </ScrollView> 
    </View> 
  ) ; 
}

// 补充样式定义(如果之前没写的话)
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  scrollViewContainer: {
    flex: 1,
  },
  contentContainer: {
    padding: 20,
  },
  searchContainer: {
    marginBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  listContainer: {
    marginTop: 20,
    padding: 10,
    backgroundColor: '#f5f5f5',
  },
});

内容的提问来源于stack exchange,提问作者Sergei Mikhailovskii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:31:44