此系列文章将整合我的 React 视频教程与 React Native 书籍中的精华部分,给大家介绍 React Native 源码学习方法及其他资源。
最后的章节给大家介绍 React Native 源码的查阅方法,以便你进行更加高阶的开发与研究时参阅,并分享了开发过程中可能遇到的众多问题的解决方案,以及与 React Native 开发相关、本书相关的一些线上资源。
15.6 React Native 源码剖析
我们在学习了 React Native 开发的方方面面之后,我们再次回到 React Native 的本质,给大家简要介绍 React Native 源码的学习方法,对 React Native 源码的整体框架做一个简单介绍,后续如果大家想深入阅读 React Native 框架的源码,希望这部分对你有所帮助,并且能从源码中学习到复杂框架的设计思想,希望大家也能“造出复杂的轮子”。
React Native 项目的 GitHub 地址为:https://github.com/facebook/react-native,源码的基本结构如图 A-1 所示。

图 A-1 React Native 源码结构
- 根目录中主要包含了项目的一些配置文件和一些描述性文档;
- 初始化项目的 React Native CLI 定义在 react-native-cli 文件夹下;
- RNTester 文件夹包含了 React Native 项目的单元测试用例以及组件、API 的使用示例代码,是一个学习 React Native 组件与 API 使用方法的宝库,这个在之前的章节有过介绍;
- React 文件夹是 iOS 原生平台的项目文件夹,用于与 React Native 的 JavaScript 代码通信;
- ReactAndroid 文件夹是 Android 原生平台的项目文件夹,用于与 React Native 的 JavaScript 代码通信;
- babel-preset 文件夹是 React Native 项目的 Babel 预配置;
- Libraries 文件夹是 React Native 源码的核心,所有的 React Native 组件与 API 的实现都在此文件夹中。
接下来我们就随便找一个组件来看看 React Native 是如何进行实现的,假设我们就来看看 Alert 组件的实现,其实通过我们在 React Native 与原生平台混合开发章节的学习,我们已经大概知道了 React Native 是如何来实现的。
我们先来看 Alert 组件 JavaScript 端的实现,Alert 组件包含的文件如图 A-2 所示。

图 A-2 Alert 组件源码结构
源码在 https://github.com/facebook/react-native/blob/master/Libraries/Alert/Alert.js。
1. ...... 2. class Alert { 3. 4. /** 5. * Launches an alert dialog with the specified title and message. 6. * 7. * See http://facebook.github.io/react-native/docs/alert.html#alert 8. */ 9. static alert( 10. title: ?string, 11. message?: ?string, 12. buttons?: Buttons, 13. options?: Options, 14. type?: AlertType, 15. ): void { 16. if (Platform.OS === 'ios') { 17. if (typeof type !== 'undefined') { 18. console.warn('Alert.alert() with a 5th "type" parameter is deprecated and will be removed. Use AlertIOS.prompt() instead.'); 19. AlertIOS.alert(title, message, buttons, type); 20. return; 21. } 22. AlertIOS.alert(title, message, buttons); 23. } else if (Platform.OS === 'android') { 24. AlertAndroid.alert(title, message, buttons, options); 25. } 26. } 27. } 28. 29. /** 30. * Wrapper around the Android native module. 31. */ 32. class AlertAndroid { 33. 34. static alert( 35. title: ?string, 36. message?: ?string, 37. buttons?: Buttons, 38. options?: Options, 39. ): void { 40. var config = { 41. title: title || '', 42. message: message || '', 43. }; 44. 45. if (options) { 46. config = {...config, cancelable: options.cancelable}; 47. } 48. // At most three buttons (neutral, negative, positive). Ignore rest. 49. // The text 'OK' should be probably localized. iOS Alert does that in native. 50. var validButtons: Buttons = buttons ? buttons.slice(0, 3) : [{text: 'OK'}]; 51. var buttonPositive = validButtons.pop(); 52
