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

React Native组件导入报错:元素类型无效问题求助

解决React Native组件导入报错:Element type is invalid

错误根源分析

你的MyWebComponent出现报错主要有三个问题:

  1. WebView导入方式错误:react-native中的WebView是命名导出,不是默认导出,直接import WebView from "react-native"会拿到整个react-native模块对象,而非WebView组件本身,这是导致"got: object"错误的核心原因。
  2. 组件props接收错误:函数组件的参数是props对象,你直接写(uri)会把整个props对象赋值给uri变量,无法正确获取传入的uri属性;同时WebView的source属性需要接收一个包含uri的对象,不是直接传字符串。
  3. 样式拼写错误:ActivityIndicator的style里jusityContent是拼写错误,应为justifyContent,会导致布局异常。

修正后的MyWebComponent代码

import { useState } from "react";
// 修正WebView的导入方式,从react-native解构导入
import { WebView, ActivityIndicator, View } from "react-native";

// 用解构赋值获取props中的uri,或者用props.uri
const MyWebComponent = ({ uri }) => {
  const [visible, setVisible] = useState(true);

  return (
    <View style={{ flex: 1 }}>
      {/* source需要传入包含uri的对象 */}
      <WebView
        source={{ uri }}
        onLoadStart={() => setVisible(true)}
        onLoadEnd={() => setVisible(false)}
      />
      {visible && (
        <ActivityIndicator
          style={{
            backgroundColor: "rgba(52, 52, 52, 0.8)",
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            // 修正拼写错误
            justifyContent: "space-around",
            flexWrap: "wrap",
            alignContent: "center",
          }}
          size="large"
        />
      )}
    </View>
  );
};

export default MyWebComponent;

额外说明

如果你的React Native版本是0.60+,官方已经把WebView从核心库移到了react-native-webview包,此时需要先安装依赖:

npm install react-native-webview
# 或者用yarn
yarn add react-native-webview

然后导入方式改为:

import { WebView } from "react-native-webview";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:35:21