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

React项目中使用React Native组件引发useContext空值读取错误原因

错误原因与解决办法

核心问题

你当前的项目是通过create-react-app创建的Web版React项目,但你导入了React Native专属的View和Text组件:

  • 你的package.json里没有安装react-native依赖,导致组件无法正常加载
  • React Native组件是为iOS/Android移动端设计的,不能直接在Web环境中运行,这就是触发Cannot read properties of null (reading 'useContext')错误的原因

解决方案

方案1:继续开发Web应用

如果你的目标是做Web项目,直接用Web兼容的标签替代React Native组件即可,比如用<div>代替View,<p>/<span>代替Text:

import './App.css';
import React from 'react';

function App() {
  return (
    <div className="App">
      <div>
        <p>Hi</p>
      </div>
    </div>
  );
}

export default App;

方案2:切换为React Native移动端项目

如果你的目标是开发iOS/Android应用,需要重新初始化正确的React Native项目:

  1. 新建React Native项目(推荐用Expo简化流程):
    npx create-expo-app FirstApp
    
  2. 进入项目后,编写标准的React Native组件(不需要Web的<div>标签):
    import React from 'react';
    import { View, Text, StyleSheet } from 'react-native';
    
    function App() {
      return (
        <View style={styles.container}>
          <Text>Hi</Text>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
    });
    
    export default App;
    
  3. 此时项目的package.json会自动包含react-native等必要依赖,可正常运行移动端组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:48:21