调试原生代码
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
查看日志
当应用运行时,您可以通过在终端执行以下命令来查看 iOS 或 Android 应用的原生日志:
# For Android:
npx react-native log-android
# Or, for iOS:
npx react-native log-ios
您也可以通过 iOS 模拟器的 Debug > Open System Log... 选项查看日志,或在 Android 设备/模拟器运行应用时,在终端执行 adb logcat "*:S" ReactNative:V ReactNativeJS:V 命令查看日志。
💡 Custom Native Logs
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)
In your native module, use the Log class to add logs that can be viewed in Logcat:
import android.util.Log;
private void log(String message) {
Log.d("YourModuleName", message);
}
To view these logs in Logcat, use this command, replacing YourModuleName with your custom tag:
adb logcat "*:S" ReactNative:V ReactNativeJS:V YourModuleName:D
iOS (Objective-C/Swift)
In your native module, use NSLog for custom logs:
NSLog(@"YourModuleName: %@", message);
Or, in Swift:
print("YourModuleName: \(message)")
These logs will appear in the Xcode console when running the app.
在原生 IDE 中调试
当处理原生代码(例如编写原生模块)时,您可以通过 Android Studio 或 Xcode 启动应用,并像开发标准原生应用那样使用原生调试功能(设置断点等)。
另一种方式是使用 React Native CLI 运行应用,然后将原生 IDE(Android Studio 或 Xcode)的调试器附加到该进程。
Android Studio
在 Android Studio 中,您可以通过菜单栏选择 "Run" > "Attach to Process...",然后选择正在运行的 React Native 应用。
Xcode
在 Xcode 中,点击顶部菜单栏的 "Debug",选择 "Attach to process" 选项,然后在 "Likely Targets" 列表中选择应用程序。