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

求助:React-Leaflet在Expo CLI创建的React Native应用中无法运行

解决Expo项目导入react-leaflet报错的问题

问题本质

react-leaflet 是基于 Leaflet 开发的 React Web 组件,依赖浏览器 DOM 环境。如果你的 Expo 项目是iOS/Android Native 端,直接导入会因为缺少 DOM API 报错;如果是Expo Web 项目,则需要额外配置 Leaflet 的资源文件才能正常运行。

场景1:Expo Native 项目(iOS/Android)

Native 环境不支持 DOM,没法直接用 react-leaflet,推荐换用 Native 原生支持的地图方案:

  • 首选 react-native-maps:Expo 官方支持的组件,完美适配 iOS/Android
    • 安装命令:expo install react-native-maps
    • 直接替换 react-leaflet 的使用逻辑,调用 Native 地图 API,完全无需依赖 DOM
  • 替代方案:用 WebView 嵌套 Leaflet 网页
    • 安装依赖:expo install react-native-webview
    • 在 WebView 中加载包含 Leaflet 逻辑的 HTML 内容,绕开 Native 环境的限制

场景2:Expo Web 项目

如果是开发 Web 端,按以下步骤配置:

  1. 安装依赖:
    npm install leaflet react-leaflet
    # 或用 yarn
    yarn add leaflet react-leaflet
    
  2. 在项目入口(比如 App.js)导入 Leaflet 的 CSS:
    import 'leaflet/dist/leaflet.css';
    
  3. 修复 Leaflet 图标路径问题(Expo Web 无法自动识别默认图标路径):
    在使用 Map 组件前添加这段代码:
    import L from 'leaflet';
    
    delete L.Icon.Default.prototype._getIconUrl;
    L.Icon.Default.mergeOptions({
      iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
      iconUrl: require('leaflet/dist/images/marker-icon.png'),
      shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
    });
    
  4. 正常使用 react-leaflet 组件:
    import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
    
    export default function MapComponent() {
      return (
        <MapContainer center={[51.505, -0.09]} zoom={13} style={{ height: '100vh', width: '100%' }}>
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <Marker position={[51.505, -0.09]}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
          </Marker>
        </MapContainer>
      );
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:03:32