5
头图

As we all know, React is a free and open source JavaScript library written by Facebook for creating highly dynamic Web UIs. Facebook later created React Native to develop cross-platform native mobile applications, using React as the core interface for developers, which enabled them to use a single code base based on React syntax to build native mobile applications for Android and iOS.

React usually renders its component changes as DOM (Document Object Model), but it can also render components as HTML to meet server-side rendering (SSR) requirements. For React Native, there used to be Proton Native, which generates cross-platform desktop applications and lets you use Qt and wxWidgets UI toolkits to render local UI elements, but it is no longer actively maintained.

Although it still has an active branch, in this article, we will introduce a more stable, actively maintained and popular project: react-native-windows . This is Microsoft's extension of React Native on the back end of Windows and macOS. It enables the same React Native-based front end to be rendered natively on Windows and macOS with platform-specific UI elements.

I will explain how to use the react-native-windows project to develop Windows desktop applications. We will also introduce how React Native syntax can be transformed into a native desktop application through the internal modules of the framework.

Set up the development environment

Make sure you have the following Windows versions installed on your computer:

  • Windows 10.0.16299.0 (aka 1709, Redstone 3 or Fall Creators Update) or higher

If your computer passes the above requirements, you can run the following commands in an elevated (with administrator rights) PowerShell window to install the required dependencies.

Set-ExecutionPolicy Unrestricted -Scope Process -Force; iex (New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/microsoft/react-native-windows/master/vnext/Scripts/rnw-dependencies.ps1')

The above command will open developer mode and install Visual Studio, Chocolatey package manager and Node.js LTS version. Also, if your computer has 8GB or more of physical memory, that would be great, because the Windows build process usually requires above-average physical memory to run.

It is recommended to use 16GB of physical memory for the above script file. If the second execution of the above script gives the following output, you can continue this tutorial.

Create a React Native Windows application

First, use the following command to create a new React Native project. This command will automatically generate a basic React Native application.

npx react-native init rnApp --template react-native@^0.64.0

The official React Native package only supports Android and iOS backends, so you need to run the following command to enable the Windows backend.

npx react-native run-windows

In addition, you can add the --useHermes option to use the Hermes JavaScript engine instead of the default Chakra.

The first build process may take a long time to complete because it will compile many C++ source files. If the build process stops due to errors, you can use the --logging option to run the same command to find these errors.

For common errors that may occur during the build process, you may also need to pay attention to the following solutions:

  • If the build process takes a lot of time, or there are compilation errors related to Chakra, please use the --useHermes option
  • If the build process raises an error about missing Windows 10 SDK, please install it from the Visual Studio installer
  • If the build process fails and certificate errors, use Visual Studio to automatically follow the steps below UWP generated by the project to create a new certificate
  • Some modules have problems with paths with spaces. Please make sure that your project path does not contain any spaces.

Once the build process is complete, you will see the UWP version of the React Native app as shown below.

The hot reload function has been enabled. In addition, the run-windows command will open the React Native debugger on Chrome. You can use Chrome DevTools to set breakpoints for your application’s JavaScript source files.

Now, let us understand what happened behind the scenes.

In React Native Windows

The core of React Native has several basic predefined React components, such as View, Text, Image, TextInput, and ScrollView. The official React Native runtime can render true native UI building blocks for the Android and iOS operating systems. The React Native team initially made the native rendering module fully extensible. Therefore, the developer community can also extend it to other platforms.

react-native-windows project adds Windows application target support. It can generate a Windows application with a true native UWP GUI from a typical React Native project. UWP applications are suitable for all popular Windows platforms, such as Windows 10, Windows 10 Mobile, Xbox One system software, and Windows Mixed Reality.

However, the JavaScript part of the application runs on a JavaScript engine similar to the original React Native project. react-native-windows project initially used the Chakra JavaScript engine, and later they integrated Facebook's Hermes JavaScript engine to improve performance.

Use react-native-windows to develop a simple application

We will make a simple UWP application, when you submit your first name and last name, it will display a greeting message. Add the following code to the App.js file.

import React from 'react';
import type {Node} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  Button,
  useColorScheme,
  View,
  Alert,
} from 'react-native';
const App: () => Node = () => {
  const isDarkMode = useColorScheme() === 'dark';
  const [firstName, setFirstName] = React.useState('');
  const [lastName, setLastName] = React.useState('');

  const styles = StyleSheet.create({
    dark: {
      color: '#fff',
      backgroundColor: '#000',
    },
    light: {
      color: '#000',
      backgroundColor: '#fff',
    },
    formItem: {
      marginBottom: 6,
    }
  });

  const backgroundStyle = {
    backgroundColor: isDarkMode ? styles.dark : styles.light,
  };

  const showFullName = () => {
    Alert.alert(`Hello ${firstName} ${lastName}`);
  };
return (
    <SafeAreaView style={backgroundStyle}>
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <View style={{padding: 12}}>
          <Text style={backgroundStyle}>First name</Text>
          <TextInput 
            style={styles.formItem} 
            value={firstName} 
            onChangeText={setFirstName}
          />
          <Text style={backgroundStyle}>Last name</Text>
          <TextInput 
            style={styles.formItem} 
            value={lastName} 
            onChangeText={setLastName}
          />
          <Button 
            style={styles.formItem}
            title='OK' 
            onPress={showFullName}
            disabled={!firstName || !lastName}>
          </Button>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};
export default App;

Now, reload the current application via React Native Debugger. You will see an application like the one below, stylized according to your theme settings.

When you click the OK button after filling in the text input, you will see a message box with a greeting as shown below.

In this sample application, we use several React Native core components and core APIs, as well as React's useState Hook to get the current user input. As you can see, we finally got native UWP UI elements from React native components.

react-native-windows extension also supports complex layout implementations because it supports Yoga friendly syntax.

The React Native developer community has also produced various excellent libraries, and some libraries also support react-native-windows . In other words, some popular React Native libraries will be available for Android, iOS and Windows applications.

By using Visual Studio to open the UWP application source code, you can publish the application.

Summarize

react-native-windows project was started at the same time as the early development phase of the official React Native project. Microsoft also recently started react-native-macos to extend React Native for the macOS backend.

react-native-windows project does render platform-specific UI elements from a JavaScript-based code base. Therefore, if you are looking for a way to build high-quality Windows desktop applications using React Native, then it is the best solution.


杭州程序员张张
11.8k 声望6.7k 粉丝

Web/Flutter/独立开发者/铲屎官