虽然 React Native 在 iOS 和 Android 中共享大部分代码,但有时您需要特定平台的代码或样式——针对不同的平台行为、设计或功能。React Native 为此提供了 Platform 模块和特定平台的文件扩展名。
Platform 模块
{ } ;
(. === ) { }
(. === ) { }
styles = {
: . === ? : ,
....({
: { : },
: { : },
}),
};
虽然 React Native 在 iOS 和 Android 中共享大部分代码,但有时您需要特定平台的代码或样式——针对不同的平台行为、设计或功能。React Native 为此提供了 Platform 模块和特定平台的文件扩展名。
{ } ;
(. === ) { }
(. === ) { }
styles = {
: . === ? : ,
....({
: { : },
: { : },
}),
};
Platform.OS 检查平台;Platform.select 为每个平台选择值——用于条件行为和样式。
→ Create separate files per platform using extensions:
Button.ios.js → used on iOS
Button.android.js → used on Android
import Button from './Button' → RN automatically picks the right file per platform
→ Good for substantially different platform implementations (cleaner than lots of if-checks)
✓ Use platform-specific code SPARINGLY — share code by default; diverge only when needed
✓ Common reasons: platform design conventions (iOS vs Material), platform-specific
features/APIs, behavior differences, platform-appropriate UX
✓ Platform module for small differences; .ios/.android files for large differences
✓ Test on BOTH platforms (a feature working on one may differ/break on the other)
理解如何编写特定平台的代码很有价值,因为即使是跨平台应用有时也需要特定平台的行为或样式,因此正确处理这一点对于真实的 React Native 应用来说是有用的实用知识。
虽然 React Native 的价值在于在 iOS 和 Android 中共享大部分代码,但真实的应用有时需要按平台进行区分——针对平台设计惯例(iOS 与 Android/Material 美学)、特定平台功能或 API、行为差异或平台适用的用户体验——理解如何处理这一点很重要。
Platform 模块(使用 Platform.OS 检查平台和 Platform.select 为每个平台选择值)处理小的差异内联——条件行为和样式。特定平台的文件(使用 .ios.js 和 .android.js 扩展,React Native 会自动选择正确的文件)干净地处理较大的差异(单独的实现而不是许多条件)。
理解何时以及如何使用这些反映了良好的判断:谨慎地使用特定平台的代码(默认共享代码,仅在真正需要时进行区分——保留 React Native 的跨平台优势),为小差异选择 Platform 模块与为大差异选择特定平台文件,以及关键是在两个平台上进行测试(因为在一个平台上工作的功能可能在另一个平台上有所不同或出现问题——这是一个常见的实际问题)。
这种平衡的方法(默认共享,必要时谨慎区分,在两个平台上测试)反映了成熟的跨平台开发。
由于跨平台应用有时确实需要特定平台的代码(针对惯例、功能或用户体验)且正确处理它(正确使用的工具谨慎使用,进行两个平台的测试)对于高质量的应用很重要,并且由于理解 Platform 模块和特定平台的文件使这成为可能,所以理解如何在 React Native 中编写特定平台的代码是有价值的、实用相关的知识——对于处理在真实应用中出现的平台差异同时保留使 React Native 有价值的跨平台代码共享很有用,反映了周全的跨平台开发。