In the past, mobile development was generally through native languages, Android through JAVA, IOS through Object-C or Swift; Developing the same APP usually requires two teams to maintain two sets of code, which is relatively expensive for small companies. Therefore, more and more companies choose React Native to develop apps. In this way, a team can maintain a set of code, which undoubtedly saves a lot of labor costs.
This article was first published in the public number [front-end one read], more exciting content please pay attention to the latest news of the public number.
Introduction of RN
React Native(RN) is a cross-platform mobile application development framework launched by Facebook in April 2015 to create Native mobile applications for Android and iOS platforms. It builds on Facebook’s JavaScript library React to create user interfaces for mobile platforms.
Official slogan: A study, write everywhere
Developers can use React Native to write Android and iOS apps that behave and look similar to Native apps. Code written with React Native can also be shared across platforms, allowing efficient development for both IOS and Android; React Native has the following advantages:
- Free, open source, and supported by a large community
- Near local performance
- Save cross-platform application development time
- Real-time and thermal overloading
But it also has some disadvantages:
- Compatibility and debugging issues
- Lack of security robustness, React Native is a JavaScript library and open source framework that has major security issues
- React Native takes a lot of time to initialize and run before the initial rendering, because JavaScript threads take time to initialize
- Native developers are still needed
So how does React Native make it cross-platform? React vs. React Native
- React is a javascript-based application development framework.
- React Native is a platform that allows users to develop cross-platform and Native mobile applications
React is only a pure JS library. It does not involve any mobile platform functions. React code needs to be parsed and executed by the JS Engine. It encapsulates a set of concepts of Virtual Dom, realizes the driving programming mode, and realizes a stateless management mechanism for complex Web UI. But there are some low-level things, such as driving native control presentation, reading and writing disks, networking, etc., that it can’t do.
However, React Native is different. JSX source code is compiled by React Native and communicates with the Native framework through the Bridge of the corresponding platform. The Bridge provides an extension of the native interface to RN embedded JS for JS to call. All native functions, such as native control drawing, image resources, local storage, network access, map location and other functions, are encapsulated into JS interfaces through Bridge and injected into JS Engine for JS invocation.
Let’s look at it concretely through a picture:
The green part is the part of our application development, mainly the JSX code we wrote; Blue represents common cross-platform code and tool engines; The yellow part is our Bridge, the code associated with each native platform; The red parts are for each system platform.
Installation and configuration of the software environment
Required software
- The JDK = = 1.8
- Android Studio
- Nodejs >= 12
React Native requires the JDK version to be 1.8. You can download the JDK for your system from the official website and configure the environment variables for your system.
Download Android Studio from the official website. Download the exe program:
In the setup screen we can check Android Virtual Device:
Android Studio installs the latest version of Android SDK by default. You can check its configuration path: Appearance & Behavior → System Settings → Android SDK; The default SDK path is in the following format:
C:\Users\ Your username \AppData\Local\Android\SdkCopy the code
RN needs environment variables to know where our SDK is installed in order to compile; Go to Control Panel -> System and Security -> System -> Advanced System Settings -> Advanced -> Environment Variables -> New and create an environment variable for ANDROID_HOME that points to the directory where we found the SDK above.
Go to control Panel -> System and Security -> System -> Advanced System Settings -> Advanced -> Environment Variables, select Path variable and click Edit to add the following directory:
%ANDROID_HOME%\platform-tools
%ANDROID_HOME%\emulator
%ANDROID_HOME%\tools
%ANDROID_HOME%\tools\bin
Copy the code
Adb connected device
The Android Debug Bridge is a command line window for interacting with emulators or Android devices from the PC. Adb is a standard CS structured tool that consists of the following three parts:
- Client: Runs on the development machine, your development PC. Used to send ADB commands.
- Deamon daemon: Runs on a debug device, i.e. a debug phone or emulator.
- Server: Runs as a daemon on the development machine, your development PC. Deamon is used to manage communication between clients in PCS and mobile phones.
There are two main ways to download and install ADB. The first way is to directly download the ADB tool package and decompress it, and then configure its directory into the environment variable Path. The second option is to take advantage of the Android Studio already installed above, which comes with the ADB tool itself, in platform-Tools in the SDK directory. If you configure the Android Studio environment variables as in the previous section, you can usually invoke adb commands directly.
Type ADB version on the command line to check the version number. If any output is displayed, the configuration is successful.
$ADB version Android Debug Bridge Version 1.0.41 version 31.0.3-7562133Copy the code
After configuring the environment, we also need to turn on the USB debugging function of the Android phone. First of all, enter the developer mode of the mobile phone. In the mobile phone Settings -> About mobile phone, click the version number for seven times to open the developer mode. Then go to Settings -> Developer Options, turn on USB debugging and some permissions to allow ADB, and the phone is configured. Let’s take a look at some common ADB commands.
adb start/kill-server
Start/kill ADB, the Server process mentioned above. Since ADB is unstable, you can kill-server and then start-server to ensure that the Server process is started. Can often solve the problem.
adb devices
List the debugging devices currently connected:
$ADB Devices List of Devices Attached CF264B8f device Emulator-5554 device 10.129.164.6:5555 deviceCopy the code
The preceding string represents the serialNumber of the mobile phone, and the following device represents the connection status of the mobile phone, including the following states:
- Device: The device is connected
- Offline: The device is disconnected or does not respond.
- Unauthorized: The device is not authorized and needs to be authorized on the device
The type of device can be seen from the serialNumber of the phone. The first letter and number represent usb connected device, emulator represents an Android emulator, and the last IP port represents wireless network connection.
If multiple devices are connected at the same time and you need to operate one of them, run the -s [serialNumber] command:
$ adb -s 9d03b4c4 shell wm size
# Physical size: 1080x1920
Copy the code
For example, in the command above, we specify the device 9D03B4C4 to get the screen resolution.
adb shell
Android system is based on the Linux kernel, so many commands in Linux have the same or similar implementation in Android, can be called in adb shell; To enter the shell interface of the device, you can use many commands:
$ adb shell
shell@PD1415BA:/ $
Copy the code
At this point, if you want to exit, you can enter exit. We can also execute it through adb shell [command] without entering the shell interface of the device.
Check all installed APK package names
adb shell pm list package
# View real-time resource usage
adb shell top
Save the screenshot to the device
adb shell screencap -p /sdcard/sc.png
# Record screen
adb shell screenrecord /sdcard/sr.mp4
# Simulate keystrokes/inputs
adb shell input keyevent <keycode>
# Slide screen
adb shell input swipe 300 1000 300 500
Copy the code
adb install/uninstall
Install and uninstall APK
Install apK
$ adb install d:\chrome.apk
Uninstalling apK
The package name is the package obtained by PM above
$ adb uninstall com.tencent.mobileqq
Copy the code
adb pull/push
Copy files between debug device and development PC, copy files from PC to device using push; Copy files from the device to the PC using pull.
$ adb push d:\1.png /sdcard/
$ adb pull /sdcard/2.png d:\temp\
Copy the code
A wireless connection
With a wireless connection, we can eliminate the need for USB to actually connect to the device and avoid problems such as unstable USB connection.
First, ensure that the ADB version is not too low (at least 30.0.0), and then connect the Android device and debugging PC to the same LAN. For the first connection, we still need to connect the mobile phone to the PC through USB, and then open the debugging port. It is recommended to choose the port that is not commonly used and not occupied:
$ adb tcpip 1314
restarting in TCP mode port: 1314
Copy the code
After the port is enabled, we can remove the USB connection, then check the IP address of the phone’s WiFi, and then use ADB to connect:
$ADB Connect connected to 192.168.0.180:1314Copy the code
After the connection, we can check whether the device is successfully connected through devices:
$ADB Devices List of Devices Attached 192.168.0.120:1314 DeviceCopy the code
Create and run RN projects
Install the React Native scaffolding and create a demo project using the scaffolding:
npm install -g react-native-cli
react-native init RNDemo
Copy the code
Next, we need an Android device, either a real machine or an Android emulator; In Android Studio, open AVD Manager to create and manage emulators. However, the official performance is not good, we can install some third-party emulators.
We recommend the Nighthian emulator here. After installing it, we can run the following commands in the project to compile and install it:
npm run android
Copy the code
It should be noted that the first compilation needs to download dependencies, which will be slow; If the configuration is all right, we should see our first RN application on the device:
Let’s take a look at the startup commands in package.json:
Start the local development server
npm run start
# To run the APP on aN iOS device, which is supported only by Mac, you need to install Xcode.
npm run ios
Android build tools are required to run the APP on An Android device.
npm run android
Run the test case.
npm test
Copy the code
NPM run start NPM run android/ios What’s the difference?
NPM Run Android /ios checks whether the device is connected while starting the development server. NPM Run Start simply starts the development server and does not install the application. If you already have the development kit on your development device, just start the server.
debugging
Developer Menu (DevMenu for short) is a Developer Menu designed for developers to debug React Native applications. ⌘ to the iOS emulator can be opened by pressing the Command + D shortcut. If it is in the Android official emulator, it is Command⌘ + M. In third-party emulators, there is usually a menu button in the sidebar. On a real Android phone, it can be opened by shaking the device.
We see the following options in the menu:
- Reload: Refreshes the page
- Change Bundle Location: Change the packaged address
- Show Element Inspect: Displays Element inspection
- Disable Fast Refresh: Fast Refresh is disabled
- Show Perf Monitor: After this function is enabled, a monitoring window is displayed, showing real-time memory usage, UI and JavaScript FPS information. Help us debug performance issues.
- Settings: set
- Enable Sampling Profiler: Enables Sampling Profiler
- Debug: Enables debugging
No apps Connected. Sending “reload” to all React Native apps failed is displayed on the development device when we only start the development server and ADB has connected to the device. To connect to our development server, select Change Bundle Location from the developer menu and type :8081.
The Show Element Inspect option brings up the hover box for Element inspection, showing the location, style, hierarchy, box model information and so on of the currently selected Element, similar to Chrome’s DevTools, which makes it easy to debug Element styles.
Debug allows us to Debug applications in Chrome in the same way we Debug applications on the Web. Click on this option, will automatically start the Chrome browser, and open a new TAB, http://localhost:8081/debugger-ui/ in this TAB, we open the developer tools, can see the log information of JS output.
You can also display all the JS files for the current debug project in the Sources Tab. And do breakpoint debugging on it.
The project structure
Being familiar with the structure of the project is the first and most important step to get started, which helps us to better understand the project. Let’s take a look at what each file in the project does:
├─ /_test_ # Test Directory ├─ / Android # Android native development directory, you can use Android Studio open native development. ├─ /ios # ios native development directory, you can use Xcode to open native development. ├── Configuration file for.BuckConfig # Buck, an efficient App project building tool for Facebook. ├─.eslintrc.js # esLint Configuration file ├─.FlowConfig # Flow Configuration file ├─.WatchmanConfig # Used to monitor bug files and file changes and start specified operations. ├─ app.js # Import ├─ app.json # for native App package Includes project name and mobile desktop display name ├─ index.js # Ios/Android entry ├─ Metro.config.js # Metro Configuration fileCopy the code
The index.js file is a packaged entry file for IOS and Android devices. For React Native projects prior to 0.49, index.ios.js and index.android.js are two separate entry files.
More front-end information please pay attention to the public number ' '[front-end reading]' '.Copy the code
If you think it’s good, check out my Nuggets page. Please visit Xie xiaofei’s blog for more articles