# @embrace-io/react-native-navigation 中文文档

规范地址：https://npmcn.com/package/%40embrace-io/react-native-navigation/

版本：7\.2\.0
npm 元数据更新时间：2026-10-08T17:11:38.854Z
中文译文更新时间：2026-11-13T15:00:08.993Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40embrace-io/react-native-navigation
原文对照：https://npmcn.com/package/%40embrace-io/react-native-navigation/?lang=original
项目主页：https://github.com/embrace-io/embrace-react-native-sdk
源码仓库：https://github.com/embrace-io/embrace-react-native-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：47.3 kB，31 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：react-native \>=0\.56\.0，react-native-navigation \*，@react-navigation/native \*
- 首次发布：2024-01-16T00:32:04.786Z
- 最新版本发布：2026-10-08T17:11:38.469Z
- 近 30 天下载量：35331（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：32（近 12 个月 9 个）

## 中文简介

为 OTel 导航仪表库创建反映导航变化的遥测数据的回放原生包

## 安装

```sh
npm install @embrace-io/react-native-navigation
```

也可以使用：`pnpm add @embrace-io/react-native-navigation`、`yarn add @embrace-io/react-native-navigation`、`bun add @embrace-io/react-native-navigation`

## README

# 反应原生拥抱 - 导航

> \[大
> 
> 本单元要求 [反应原生拥抱 SDK](https://www.npmjs.com/package/@embrace-io/react-native) 财务报告和审定财务报表 页:1 [反应原生拥抱追踪提供者](https://www.npmjs.com/package/@embrace-io/react-native-tracer-provider)。 。 。 .

此套件使用 Enbrace 的 React 原生 SDK 和 OpenTeleometer Tracer 提供器来收集基于 Navigation 的周边遥测数据 [输出路由器](https://github.com/expo/expo/tree/main/packages/expo-router), (中文(简体) ), [@ react-navigation/ 本地语](https://github.com/react-navigation/react-navigation) 财务报告和审定财务报表 [反应-内在导航](https://wix.github.io/react-native-navigation/)。 。 。 .

## 安装组件

无 :

```sh
npm install @embrace-io/react-native-navigation
```

线条 :

```sh
yarn add @embrace-io/react-native-navigation
```

## 在代码中设置

使用 `expo-router`数字 :

```javascript
import React from 'react';
import {useEmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider";
import {EmbraceNavigationTracker} from "@embrace-io/react-native-navigation";
import {Stack, useNavigationContainerRef} from 'expo-router';
import {useEmbrace} from "@embrace-io/react-native";

const App = () => {
  const {isStarted} = useEmbrace({
    ios: {
      appId: "__APP_ID__"
    }
  });

  // The provider is something you need to configure and pass down as prop into the `<EmbraceNavigationTracker />` component 
  // If your choice is not to pass any custom tracer provider, the component will use the global one.
  // In both cases you have to make sure a tracer provider is registered BEFORE you attempt to record the first span (otherwise some initial telemetry can be missed).
  const {tracerProvider, isLoading: isLoadingTracerProvider} =
    useEmbraceNativeTracerProvider({}, isStarted);

  // If you do not use `expo-router` the same hook is also available in `@react-navigation/native` since `expo-router` is built on top of it.
  // Make sure this ref is passed also to the navigation container at the root of your app (if not, the ref would be empty and you will get a console.warn message instead).
  const expoNavigationRef = useNavigationContainerRef();

  if (isLoadingTracerProvider || tracerProvider === null) {
    return (
      <View>
        <View>
          <Text>Loading Tracer Provider...</Text>
        </View>
      </View>
    );
  }

  return (
    <EmbraceNavigationTracker
      ref={expoNavigationRef}
      tracerProvider={tracerProvider}
      // These static attributes will be passed into each created span
      screenAttributes={{
          "static.attribute": 123456,
          "custom.key": "abcd...",
      }}>
      <Stack>
        <Stack.Screen name="(tabs)" options={{headerShown: false}} />
        <Stack.Screen name="+not-found" />
        ... rest of stack
      </Stack>
    </EmbraceNavigationTracker>
  );
};

export default App;
```

如果你是纯粹使用 [@ react-navigation/ 本地语](https://github.com/react-navigation/react-navigation)数字 :

```javascript
import React from 'react';
import {useEmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider";
import {EmbraceNavigationTracker} from "@embrace-io/react-native-navigation";
import {
  NavigationContainer,
  useNavigationContainerRef,
} from "@react-navigation/native";
import {createBottomTabNavigator} from "@react-navigation/bottom-tabs";
import {useEmbrace} from "@embrace-io/react-native";
import CartPage from "screens/CartPage";
import CheckoutPage from "screens/CheckoutPage";

const Tab = createBottomTabNavigator();

const App = () => {
  const {isStarted} = useEmbrace({
    ios: {
      appId: "__APP_ID__"
    }
  });

  // The provider is something you need to configure and pass down as prop into the `EmbraceNavigationTracker` component 
  // If your choice is not to pass any custom tracer provider, the <EmbraceNavigationTracker /> component will use the global one.
  // In both cases you have to make sure a tracer provider is registered BEFORE you attempt to record the first span.
  const {tracerProvider, isLoading: isLoadingTracerProvider} =
    useEmbraceNativeTracerProvider({}, isStarted);

  // Tip! as of now if you inspect the source code of `useNavigationContainerRef` from `@react-navigation/native` you will see that it returns `navigation.current` instead of the entire shape of a reference
  const navigationRefVal = useNavigationContainerRef();
  // We need here the entire shape, so we re-create it and pass it down into the `ref` prop for the `EmbraceNavigationTracker` component.
  const navigationRef = useRef(navigationRefVal);

  if (isLoadingTracerProvider || tracerProvider === null) {
    return (
      <View>
        <View>
          <Text>Loading Tracer Provider...</Text>
        </View>
      </View>
    );
  }

  return (
    // `NavigationContainer` is waiting for what `useNavigationContainerRef` is returning (both exported from `@react-navigation/native`)
    <NavigationContainer ref={navigationRefVal}>
      <EmbraceNavigationTracker
        ref={navigationRef}
        tracerProvider={tracerProvider}
        screenAttributes={{
          "static.attribute": 123456,
          "custom.key": "abcd...",
        }}>
        <Tab.Navigator
          screenOptions={{
            tabBarLabelPosition: "beside-icon",
            tabBarIconStyle: {display: "none"},
          }}>
          <Tab.Screen
            name="cart"
            options={{
              tabBarAccessibilityLabel: "Cart",
            }}
            component={CartPage}
          />
          <Tab.Screen
            name="checkout"
            options={{
              tabBarAccessibilityLabel: "Checkout",
            }}
            component={CheckoutPage}
          />
          ... rest of tabs
        </Tab.Navigator>
      </EmbraceNavigationTracker>
    </NavigationContainer>
  );
};

export default App;
```

注:如果使用 [@ react-navigation/ 本地语](https://github.com/react-navigation/react-navigation) 您需要将您的整个应用程序与 `NavigationTracker` 内容载于其正式文件.

使用时 [反应-内在导航](https://wix.github.io/react-native-navigation/) 您也可以跟踪导航变化. 一定要把入口的视图包起来 `<EmbraceNativeNavigationTracker />` 组件并尽快初始化嵌入,以避免丢失遥测数据.

```javascript
// index.ts
import React, {useRef} from "react";
import {EmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider";
import {TracerProvider} from "@opentelemetry/api";
import {EmbraceNativeNavigationTracker} from "@embrace-io/react-native-navigation";
import {initialize} from "@embrace-io/react-native";
import {Navigation} from "react-native-navigation";
import {HomeScreen} from "screens/HomeScreen";

const initApp = async () => {
  // this example is showing how we can initialize Embrace not using hooks
  await initialize({
    sdkConfig: {
      ios: {appId: "__APP_ID__"},
    },
  });

  let embraceTracerProvider: TracerProvider;
  try {
    embraceTracerProvider = new EmbraceNativeTracerProvider();
  } catch (e) {
    console.log(
      "Error creating `EmbraceNativeTracerProvider`. Will use global tracer provider instead",
      e,
    );
  }

  Navigation.registerComponent(
    "HomeScreen",
    () =>
      (props) => {
        // make sure to wrap the events registry instance in a React ref
        const navRef = useRef(Navigation.events());

        return (
          <EmbraceNativeNavigationTracker
            ref={navRef}
            tracerProvider={embraceTracerProvider}
            screenAttributes={{
              "test.attr": 98765,
              dev: true,
            }}>
            <HomeScreen {...props} />
          </EmbraceNativeNavigationTracker>
        );
      },
    () => HomeScreen,
  );

  // ... rest of registration and configuration
};

// root of the app
initApp();
```

## 禁用本地屏幕的自动跟踪

拥抱还自动收集本地屏幕, 如果您不想在会话中看到本地组件, 您可以禁用它 :

### Java 脚本

```javascript
const App = () => {
  const {isPending, isStarted} = useEmbrace({
    ios: {
      appId: "__APP_ID__",
      disableAutomaticViewCapture: true, // disabling the feature just for iOS
    },
  });


  if (isPending) {
    return (
      <View>
        <Text>Loading Embrace</Text>
      </View>
    );
  } else {
    if (!isStarted) {
      console.log('An error occurred during Embrace initialization');
    }
  }

  // regular content of the application
  return (
    ...  
  );
}

export default App
```

### 机器人

转到你的 `embrace-config.json` 内部 `android/app/src/main` 编辑 `sdk_config` 键. 通过这些更改, 您的文件至少应该看起来如下 :

```json
{
  "app_id": "APP_ID",
  "api_token": "API_TOKEN",
  "sdk_config": {
    "app_framework": "react_native",
    "view_config": {
      "enable_automatic_activity_capture": false // disabling automatic capture
    }
  }
}
```

### iOS: (英语)

如果您使用自动安装脚本或遵循手动步骤设置了iOS SDK,那么您可以 修改设置在 `EmbraceInitializer.swift` 删除视图抓取服务,参见 [配置 iOS SDK](https://npmcn.com/ios/open-source/integration/embrace-options/) 详情:

```swift
import Foundation
import EmbraceIO
import EmbraceCrash

@objcMembers class EmbraceInitializer: NSObject {
    static func start() -> Void {
        do {
         
            try Embrace
                .setup(
                    options: Embrace.Options(
                        appId: "__APP_ID__",
                        platform: .reactNative,
                        captureServices: CaptureServiceBuilder()
                            .addDefaults()
                            .remove(ofType: ViewCaptureService.self)
                            .build(),
                        crashReporter: EmbraceCrashReporter()
                    )
                )
                .start()
        } catch let e {
            print("Error starting Embrace \(e.localizedDescription)")
        }
    }
}
```

## 常见问题

### @embrace-io/react-native-navigation 是什么？

为 OTel 导航仪表库创建反映导航变化的遥测数据的回放原生包

### 如何安装 @embrace-io/react-native-navigation？

在项目目录运行 npm install @embrace-io/react-native-navigation，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react-native（\>=0\.56\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @embrace-io/react-native-navigation 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @embrace-io/react-native-navigation 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @embrace-io/react-native-navigation 可以商用吗？

@embrace-io/react-native-navigation 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @embrace-io/react-native-navigation 的下载量有多少？

根据 npm 官方下载统计，@embrace-io/react-native-navigation 在 2026/10/14 – 2026/11/12 这 30 天内被下载 35,331 次，日均约 1,178 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @embrace-io/react-native-navigation 还在维护吗？

最新版本 7\.2\.0 发布于 2026/10/09（1 个月前）；至今共发布 32 个版本，其中过去 12 个月发布了 9 个；首次发布于 2024/01/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

