Skip to main content

调试原生代码

仅包含原生代码的项目

The following section only applies to projects with native code exposed. If you are using the managed Expo workflow, see the guide on prebuild to use this API.

访问日志

¥Accessing Logs

你可以在应用运行时在终端中使用以下命令显示 iOS 或 Android 应用的原生日志:

¥You can display the native logs for an iOS or Android app by using the following commands in a terminal while the app is running:

shell
# For Android:
npx react-native log-android
# Or, for iOS:
npx react-native log-ios

你还可以通过 iOS 模拟器中的“调试”>“打开系统日志...”或在 Android 应用在设备或模拟器上运行时在终端中运行 adb logcat "*:S" ReactNative:V ReactNativeJS:V 来访问这些内容。

¥You may also access these through Debug > Open System Log… in the iOS Simulator or by running adb logcat "*:S" ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.

💡 Custom Native Logs

如果你正在编写 Native 模块并希望将自定义日志添加到模块中以进行调试,则可以使用以下方法:

¥If you are writing a Native Module and want to add custom logs to your module for debugging purposes, you can use the following method:

Android (Java/Kotlin)

在你的原生模块中,使用 Log 类添加可以在 Logcat 中查看的日志:

¥In your native module, use the Log class to add logs that can be viewed in Logcat:

java
import android.util.Log;

private void log(String message) {
Log.d("YourModuleName", message);
}

要在 Logcat 中查看这些日志,请使用此命令,将 YourModuleName 替换为你的自定义标签:

¥To view these logs in Logcat, use this command, replacing YourModuleName with your custom tag:

shell
adb logcat "*:S" ReactNative:V ReactNativeJS:V YourModuleName:D

iOS (Objective-C/Swift)

在你的原生模块中,使用 NSLog 进行自定义日志:

¥In your native module, use NSLog for custom logs:

objective-c
NSLog(@"YourModuleName: %@", message);

或者,在 Swift 中:

¥Or, in Swift:

swift
print("YourModuleName: \(message)")

运行应用时,这些日志将出现在 Xcode 控制台中。

¥These logs will appear in the Xcode console when running the app.

在原生 IDE 中调试

¥Debugging in a Native IDE

使用原生代码时,例如编写原生模块时,你可以从 Android Studio 或 Xcode 启动应用,并利用原生调试功能(设置断点等),就像构建标准原生应用一样 。

¥When working with native code, such as when writing native modules, you can launch the app from Android Studio or Xcode and take advantage of the native debugging features (setting up breakpoints, etc.) as you would in case of building a standard native app.

另一种选择是使用 React Native CLI 运行应用,并将原生 IDE(Android Studio 或 Xcode)的原生调试器附加到进程。

¥Another option is to run your application using the React Native CLI and attach the native debugger of the native IDE (Android Studio or Xcode) to the process.

Android Studio

在 Android Studio 上,你可以通过菜单栏上的 "运行" 选项,单击 "附加到进程..." 并选择正在运行的 React Native 应用来完成此操作。

¥On Android Studio you can do this by going on the "Run" option on the menu bar, clicking on "Attach to Process..." and selecting the running React Native app.

Xcode

在 Xcode 上,单击顶部菜单栏上的 "调试",选择 "附加到进程" 选项,然后在 "可能的目标" 列表中选择应用。

¥On Xcode click on "Debug" on the top menu bar, select the "Attach to process" option, and select the application in the list of "Likely Targets".