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

React Native开发报错:Element type is invalid,请求排查

React Native Expo 组件渲染错误排查

错误信息

Element type is invalid: expected a string(for built-in components)or a class/function(for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in or you might have mixed up default and named imports.
检查'GoalInput'的render方法

代码片段

App.js 部分

import { useState } from "react";
import { StyleSheet, View, FlatList, Button } from "react-native";
import { StatusBar } from "expo-status-bar";
import GoalItem from "./components/GoalItem";
import GoalInput from "./components/GoalInput";

return (
    <>
      <StatusBar/>
      <View>
        <Button onPress={startAddGoalHandler}/>
        <GoalInput
          visible={modalIsVisible}
          onAddGoal={addGoalHandler}
          onCancel={endAddGoalHandler}
        />
      </View>
    </>
  );

GoalInput.js 部分

import { useState } from "react";
import { StyleSheet,Button,TextInput,View,Model,Image} from "react-native";

const GoalInput = (props) => {
  const [enteredGoalText, setEnteredGoalText] = useState("");

  const goalInputHandler = (enteredText) => {
    setEnteredGoalText(enteredText);
  };

  const addGoalHandler = () => {
    props.onAddGoal(enteredGoalText);   
    setEnteredGoalText("");
  };

  return (
    <Model visible={props.visible} animationType="slide">
      <View>
        <Image
          source={require("../assets/Images/goal.png")}
        />
        <TextInput
          onChangeText={goalInputHandler}
          value={enteredGoalText}
        />
        <View>
          <View>
            <Button title="Add Goal" onPress={addGoalHandler} color="#b180f0" />
          </View>
          <View>
            <Button title="Cancel" onPress={props.onCancel} color="#f31282" />
          </View>
        </View>
      </View>
    </Model>
  );
};

export default GoalInput;

错误根源与修复方案

1. 核心错误:Modal 组件拼写错误

在GoalInput.js中,你将React Native的Modal组件误写为Model——React Native不存在名为Model的内置组件,导致导入的Model为undefined,这直接触发了"Element type is invalid"错误。

修复步骤:

  • 修改导入语句中的组件名称:
    import { StyleSheet, Button, TextInput, View, Modal, Image} from "react-native";
    
  • 将返回JSX中的<Model>标签替换为<Modal>:
    return (
      <Modal visible={props.visible} animationType="slide">
        {/* 其余内容保持不变 */}
      </Modal>
    );
    

2. 次要问题:App.js 中的 Button 缺少 title 属性

App.js内的<Button onPress={startAddGoalHandler}/>未设置title属性,会导致按钮无法正常渲染,建议补充:

<Button title="Add New Goal" onPress={startAddGoalHandler}/>

3. 可选优化:完善 TextInput 属性

为提升用户体验,可给TextInput添加占位提示、自动大写等属性:

<TextInput
  placeholder="Enter your goal"
  autoCapitalize="sentences"
  onChangeText={goalInputHandler}
  value={enteredGoalText}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:16:21