React 组件名称

了解 Sentry 的 React Native SDK 如何让你监控组件。

你可以设置 Sentry 的 React Native SDK 使用 React 组件名称而不是元素名称。这样你就不必查看像这样的通用名称:

Copied
View > Touchable > View > Text

你可以确切地看到使用了哪个 React 组件,如下例所示:

Copied
MyCard (View, MyCard.ts) > MyButton (Touchable, MyCard.ts) > View > Text

一旦你启用了捕获功能,你将能够在面包屑和跨度中看到与之交互的具体组件名称。这消除了通过查看通用名称来猜测的不确定性,尤其是在你的应用程序规模较大时,这种不确定性更难解决。

我们正在努力发布更多未来将利用组件名称捕获的功能,并强烈建议你配置项目以使用它。

  • 安装 React Native SDK 5.25.0-alpha.3 或更新版本。
  • 确保你要捕获的 React 组件在 .jsx.tsx 文件格式中。

@sentry/react-native/metro 插件添加到你的 Metro 配置并启用 reactComponentAnnotation 选项:

metro.config.js
Copied
const { getDefaultConfig } = require("@react-native/metro-config");
const { withSentryConfig } = require("@sentry/react-native/metro");

const config = getDefaultConfig(__dirname);
module.exports = withSentryConfig(config, {
  annotateReactComponents: true,
});

Sentry React Native Metro 插件应用了 @sentry/babel-plugin-component-annotate,该插件在构建时解析应用程序的 JSX 源代码并为其添加额外的 data 属性。这些属性会出现在应用程序构建的节点上,指示每个节点来源的 React 组件名称和文件。

这是一个在文件 myAwesomeComponent.jsx 中名为 MyAwesomeComponent 的组件示例:

Copied
function MyAwesomeComponent() {
  return <Text>This is a really cool and awesome component!</Text>;
}

如果你的打包工具应用了插件并构建了项目,生成的节点将会如下所示:

Copied
<Text
  data-sentry-component="MyAwesomeComponent"
  data-sentry-source-file="myAwesomeComponent.jsx"
>
  This is a really cool and awesome component!
</Text>

Sentry 浏览器 SDK 会从这些 data 属性中提取值并在你的组件被交互时收集它们。

如果报告的事件中缺少组件名称,可能是注释未添加到 JS 包中。要排查此问题:

  1. 检查 Metro 生成的 JS 包是否包含注释,通过在包中搜索 data-sentry-component 键来确认。
  2. 如果注释缺失且你使用的是没有框架的 React Native,检查 config.transformer.babelTransformerPath 是否在传递给 withSentryConfig(config) 之前已设置。如果你是 Expo 用户并使用 const config = getSentryExpoConfig(__dirname),请确保 getSentryExpoConfig 设置的 config.transformer.babelTransformerPath 没有被覆盖。
  3. 使用 export SENTRY_LOG_LEVEL=debug 启用调试日志以验证 Sentry 是否检测到了默认转换器并且 Sentry Babel 转换器已执行。