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

如何在Expo构建的React Native应用中动态获取Metro服务地址?

在Expo应用内动态获取Metro的nativeRuntimeUrl地址

当然可以实现,Expo提供了内置API来获取这个地址,具体通过expo-constants库就能完成:

步骤1:安装依赖(未安装时执行)

npx expo install expo-constants

步骤2:在组件中获取并展示地址

在React Native组件里导入expo-constants,读取对应属性即可拿到目标地址:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  // 优先读取nativeRuntimeUrl,本地开发环境fallback到expoConfig.uri
  const metroRuntimeUrl = Constants.expoConfig?.extra?.eas?.nativeRuntimeUrl 
    || Constants.expoConfig?.uri;

  return (
    <View style={styles.container}>
      <Text style={styles.text}>当前Metro运行地址:</Text>
      <Text style={styles.urlText}>{metroRuntimeUrl || '无法获取地址'}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  text: {
    fontSize: 16,
    marginBottom: 10,
  },
  urlText: {
    fontSize: 18,
    color: '#2196F3',
    textAlign: 'center',
  },
});

补充说明

  • Constants.expoConfig.extra.eas.nativeRuntimeUrl 就是你提到的Expo源码中nativeRuntimeUrl返回的值,多在EAS构建场景下可用
  • 本地执行npx expo start时,Constants.expoConfig.uri会返回终端显示的类似exp://192.168.100.8:8081的地址
  • 生产构建环境中该值可能不存在,建议添加空值兜底处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:31:01