使用React Native Web构建适合移动设备的Web应用

Over the years, building web applications that are mobile friendly has become easier with the advent of media queries and the introduction of service workers. Using media queries, we could make web applications that different shapes when viewed on mobile devices. Service workers, with their powerful features, present web applications with powers only native applications have been known to possess — push notifications, background sync, etc.

多年来,随着媒体查询的出现和服务人员的引入,构建移动友好的Web应用程序变得更加容易。 使用媒体查询,我们可以使Web应用程序在移动设备上查看时具有不同的形状。 服务工作者以其强大的功能为Web应用程序提供仅已知本机应用程序具有的功能-推送通知,后台同步等。

React Native is a multi-platform solution developed by Facebook that lets you build mobile apps using JavaScript. These mobile apps are considered multi-platform because they’re written once and deployed across many platforms, like Android, iOS and the web. Today, we’ll see how we can utilize this powerful technology to build platform-focused applications on the web.

React Native是Facebook开发的一种多平台解决方案,可让您使用JavaScript构建移动应用程序。 这些移动应用程序被认为是多平台的,因为它们只编写一次并部署在许多平台上,例如Android,iOS和Web。 今天,我们将看到如何利用这项强大的技术在Web上构建针对平台的应用程序。

We’ll be building a simple application that displays user information from a random API using React Native components like ScrollView, Text and Image.

我们将构建一个简单的应用程序,该应用程序使用React Native组件(例如ScrollView,Text和Image)显示来自随机API的用户信息。

The library we’ll be using to build the demo is called React Native Web, "React Native for Web makes it possible to run React Native components and APIs on the web using React DOM”.

我们将用于构建演示的库称为React Native Web,“ React Native for Web使使用React DOM在Web上运行React Native组件和API成为可能”。

We’ll be building a simple application that will run both on the web and mobile using the React Native Web library, the application displays user information from a random API using React native components like ScrollView, Text, Image etc.

我们将构建一个简单的应用程序,使用React Native Web库在Web和移动设备上运行,该应用程序使用React Native组件(例如ScrollView,Text,Image等)显示来自随机API的用户信息。

先决条件 ( Prerequisites )

To follow this tutorial, you’ll need to have Node > 6.0 installed. You’ll also need a package manager NPM (this comes packaged with Node) or Yarn(follow the installation guide here).

要遵循本教程,您需要安装Node > 6.0。 您还需要一个软件包管理器NPM(Node随附)或Yarn(按照此处的安装指南)。

Basic knowledge of JavaScript and React is also required. You can follow the official React tutorial here to get up to speed with React.

还需要JavaScript和React的基础知识。 您可以在此处关注官方的React教程,以快速了解React。

入门 ( Getting started )

Before we get started, we’ll need to set up the project and install project dependencies. We’ll be making use of Create React App to bootstrap our application. We’re using Create React App because it can be configured to alias React Native. We’ll be installing polyfills for some of the latest JavaScript APIs like Promise, Array.from, etc., as the transpiler doesn’t provide those.

在开始之前,我们需要设置项目并安装项目依赖项。 我们将使用Create React App引导我们的应用程序。 我们正在使用Create React App,因为它可以配置为别名React Native。 我们将为某些最新JavaScript API(例如PromiseArray.from等)安装polyfills,因为transpiler不提供这些功能。

To bootstrap your application using Create React App, run the following command:

要使用Create React App引导您的应用程序,请运行以下命令:

yarn create react-app random-people
              or
    npx create-react-app random-people

Run the following command to install the project’s development dependencies:

运行以下命令以安装项目的开发依赖项:

yarn add --dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo
              ornpm install --save-dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo

The babel-plugin-module-resolver is a plugin that resolves your project modules when compiling with Babel. We’ll use this package to alias react-native to react-native-web when setting up the project config.

babel-plugin-module-resolver是一个插件,可在使用Babel进行编译时解析您的项目模块。 设置项目配置时,我们将使用此软件包将react-native别名为react-native-web。

To build and run our application, we’ll be using Expo. Expo is an open-source toolchain built around React Native for building Android and iOS applications. It provides access to the system’s functionality like the Camera, Storage, etc.

为了构建和运行我们的应用程序,我们将使用Expo。 Expo是一个围绕React Native构建的开源工具链,用于构建Android和iOS应用程序。 它提供对系统功能(如摄像机,存储设备等)的访问。

Install the expo-cli by running the following command:

通过运行以下命令来安装expo-cli:

yarn global add expo-cli
            ornpm i g expo-cli

The next step is to install expo locally, alongside React Native and React Native Web. Run the command below to install the packages:

下一步是在本地安装expo,以及React Native和React Native Web。 运行以下命令以安装软件包:

yarn add expo react-native react-native-web react-art
            ornpm i expo react-native react-native-web react-art

After downloading the packages needed to run and build the application, the next step is to setup the configuration files. Create a file called .babelrc in the root of your project and update it with the following:

下载运行和构建应用程序所需的软件包后,下一步是设置配置文件。 在项目的根目录中创建一个名为.babelrc的文件,并使用以下内容对其进行更新:

//.babelrc{
      "presets": ["babel-preset-expo"],
      "env": {
        "development": {
          "plugins": ["transform-object-rest-spread", "transform-react-jsx-source"]
        }
      },
      "plugins": [
        [
          "module-resolver",
          {
            "alias": {
              "^react-native$": "react-native-web"
            }
          }
        ]
      ]
    }

Create a file named app.json. This file is used to configure parts of your application that don’t belong in the code like the application name, description, sdkVersion, etc. You can find the options available for the app.json file here.

创建一个名为app.json的文件。 该文件用于配置应用程序中不属于代码的部分,例如应用程序namedescriptionsdkVersion等。您可以在此处找到可用于app.json文件的选项。

Let’s update the package.json file to include commands for running our application on Android and iOS emulators. Also, we’ll include the main field referencing the App.js file. This file will act as the entry file for the expo-cli. Open the package.json file in a file editor of choice:

让我们更新package.json文件,使其包含用于在Android和iOS模拟器上运行我们的应用程序的命令。 另外,我们将包括引用App.js文件的main字段。 该文件将充当expo-cli的入口文件。 在选择的文件编辑器中打开package.json文件:

// package.json
    {
      "name": "random-people",
      "version": "0.1.0",
      "private": true,
      "main": "./App.js",
      ...
      "scripts": {
        "start-web": "react-scripts start",
        "build-web": "react-scripts build",
        "test-web": "react-scripts test",
        "eject-web": "react-scripts eject",
        "start-native" : "expo start",
        "android": "expo android",
        "ios": "expo ios",
        "build:ios": "expo build:ios",
        "build:android": "expo build:android",
      },
      ...
    }

Run npm run start-web to run the application and visit http://localhost:3000 to view the application.

运行npm run start-web来运行该应用程序,然后访问http:// localhost:3000以查看该应用程序。

家庭组件 ( Home component )

Our application is a simple demo that displays users via the random user API. Using the API, we’ll get display a name and avatar of the returned users through some of the components provided by React Native. Within the src/ directory, create a file named home.js. Open this file using an editor and update it with the snippet below:

我们的应用程序是一个简单的演示,通过随机用户API显示用户。 使用API​​,我们将通过React Native提供的某些组件显示返回用户的名称和头像。 在src/目录中,创建一个名为home.js的文件。 使用编辑器打开此文件,并使用以下代码段对其进行更新:

//home.js
    import React from "react";
    import {
      ScrollView,
      ActivityIndicator,
      StyleSheet
    } from "react-native";

    class Home extends React.Component {
      state = {
        users: [],
        loading: true
      };
      componentDidMount() {
        // TODO: get users
      }

      render() {
        return (
          <ScrollView
            noSpacer={true}
            noScroll={true}
            style={styles.container}
          >
           <ActivityIndicator
                style={[styles.centering, styles.gray]}
                color="#ff8179"
                size="large"
              />
          </ScrollView>
        );
      }
    }

    var styles = StyleSheet.create({
      container: {
        backgroundColor: "whitesmoke"
      },
      centering: {
        alignItems: "center",
        justifyContent: "center",
        padding: 8,
        height: '100vh'
      },
    });

    export default Home;

In the snippet above, the Home component renders a ScrollView component that houses the component’s elements. Currently, the component displays an ActivityIndicator; this will be replaced by the user list when the call to the API is complete.

在上面的代码段中, Home组件呈现了一个ScrollView组件,其中包含该组件的元素。 当前,该组件显示一个ActivityIndi​​cator ; API调用完成后,它将被用户列表替换。

We create styles for the elements using the StyleSheet component. This allows us to style the component using properties similar to CSS properties.

我们使用StyleSheet组件为元素创建样式。 这使我们可以使用类似于CSS属性的属性来为组件设置样式。

Let’s create a method that gets random users from the Random User API. This method will be called during the componentDidMount lifecycle. Update the home.js component to include the getUsers method:

让我们创建一个从“随机用户” API获取随机用户的方法。 在componentDidMount生命周期中将调用此方法。 更新home.js组件以包含getUsers方法:

// home.js
    import React from 'react';
    ...

    class Home extends React.Component {
      state = {
        ...
      };
      componentDidMount() {
        this.getUsers();
      }

      async getUsers() {
        const res = await fetch("https://randomuser.me/api/?results=20");
        const { results } = await res.json();
        this.setState({ users: [...results], loading: false });
      }
      ...
    }

We can easily make requests using the native Fetch API. Results from the request are parsed and added to state. When the request is complete, we’ll hide the ActivityIncidator by setting loading to false.

我们可以使用本地Fetch API轻松发出请求。 请求的结果将被解析并添加到状态中。 请求完成后,我们通过将loading设置为false来隐藏ActivityIncidator

应用程序组件 ( App component )

The AppComponent holds the logic for the application. We’ll update the default view created by Create React App to suit that of our application by adding logic to display native components.

AppComponent包含应用程序的逻辑。 我们将通过添加显示本机组件的逻辑来更新Create React App创建的默认视图以适合我们的应用程序。

Create a new file named App.js in the root of your project. This file will be similar to the src/App.js file. The root App.js file will act as the entry file for expo, and the src/App.js file exists for Create React App builds. Update both files with the snippet below:

在项目的根目录中创建一个名为App.js的新文件。 该文件将类似于src/App.js文件。 根App.js文件将充当expo的入口文件,并且src/App.js文件存在于Create React App构建中。 使用以下代码段更新两个文件:

import React from 'react';
    import {
      AppRegistry,
      StyleSheet,
      View,
    } from 'react-native';
    import Home from './home'

    class App extends React.Component {
      render() {
        return (
          <View style={styles.appContainer}>
            <Home />
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      appContainer: {
        flex: 1,
      },
    });

    AppRegistry.registerComponent('App', () => App);

    export default App;

In the snippet above, we register our App component using the AppRegistry. The AppRegistry is the entry point of React Native applications.

在上面的代码段中,我们使用AppRegistry注册了我们的App组件。 AppRegistry是React Native应用程序的入口点。

创建用户项目 ( Creating user item )

Each user item will be displayed using a View component. The View component is an important building block that supports layout using flexbox, styling and accessibility. The View component of each item will be within a SwipeableFlatList. Each item will display the user’s avatar, name and email. Create a file called user-item.js within the src/ folder and update it with the code below:

每个用户项目将使用“ View组件显示。 View组件是一个重要的构建块,它支持使用flexbox,样式和可访问性进行布局。 每个项目的View组件都在SwipeableFlatList中。 每个项目都会显示用户的头像,姓名和电子邮件。 在src/文件夹中创建一个名为user-item.js的文件,并使用以下代码对其进行更新:

// user-item.js

    import React from "react";
    import { View, Image, Text, StyleSheet } from "react-native";

    const UserItem = ({ item: user }) => {
      return (
        <View style={styles.row}>
          <Image style={styles.rowIcon} source={user.picture.medium} />
          <View style={styles.rowData}>
            <Text style={styles.rowDataText}>{`${user.name.title} ${
              user.name.first
            } ${user.name.last}`}</Text>
            <Text style={styles.rowDataSubText}>{user.email}</Text>
          </View>
        </View>
      );
    };

    const styles = StyleSheet.create({
      row: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        padding: 15,
        marginBottom: 5,
        backgroundColor: "white",
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: "rgba(0,0,0,0.1)"
      },
      rowIcon: {
        width: 64,
        height: 64,
        marginRight: 20,
        borderRadius: "50%",
        boxShadow: "0 1px 2px 0 rgba(0,0,0,0.1)"
      },
      rowData: {
        flex: 1
      },
      rowDataText: {
        fontSize: 15,
        textTransform: "capitalize",
        color: "#4b4b4b"
      },
      rowDataSubText: {
        fontSize: 13,
        opacity: 0.8,
        color: "#a8a689",
        marginTop: 4
      }
    });

    export default UserItem;

To display the avatar of each user, we make use of the Image component. The component takes a source prop which acts the src which we are used to on the web. The component can be styled further as we have using styles.rowIcon property.

为了显示每个用户的头像,我们使用了Image组件。 该组件带有一个source道具,该道具充当我们习惯于在网络上使用的src 。 我们可以使用styles.rowIcon属性来进一步设置组件的样式。

Next, we’ll create the UserList to display each UserItem.

接下来,我们将创建UserList来显示每个UserItem

创建用户列表 ( Creating users list )

The FlatList component is one that is performant in its list rendering methods. It lazy-loads the items within the list, and only loads more items when the user has scrolled to the bottom of the list. The SwipeableFlatList is a wrapper around the FlatList provided by React Native Web, which makes each item within the list swipeable — so each item will reveals a set of actions when swiped.

FlatList组件在其列表呈现方法中表现出色。 它会延迟加载列表中的项目,并且仅当用户滚动到列表底部时才加载更多项目。 SwipeableFlatList是React Native Web提供的FlatList的包装,它使列表中的每个项目都可滑动—因此,每一项在滑动时都会显示一组操作。

Let’s create the SwipeableFlatList for the users returned from the API. Import the SwipeableFlatList component from the react-native package and update the render function to display the list. Create a file called user-list.js and update the file with the following:

让我们为从API返回的用户创建SwipeableFlatList 。 从react-native包中导入SwipeableFlatList组件,并更新render函数以显示列表。 创建一个名为user-list.js的文件,并使用以下内容更新该文件:

import React from "react";
    import { SwipeableFlatList } from "react-native";
    import UserItem from "./user-item";

    const UserList = ({ users }) => {
      return (
        <SwipeableFlatList
          data={users}
          bounceFirstRowOnMount={true}
          maxSwipeDistance={160}
          renderItem={UserItem}
        />
      );
    };

    export default UserList;
  • data: this prop represents the data that will be fed to each item within the list. The data prop is usually an array.

    data :此属性代表将被馈送到列表中每个项目的数据。 data属性通常是一个数组。
  • bounceFirstRowOnMount: if true, it triggers on a bounce animation on the first item in the list, signifying that it has hidden actions within.

    bounceFirstRowOnMount :如果为true,则在列表中的第一项上触发跳动动画,表示其内部具有隐藏的动作。
  • maxSwipeDistance: this prop sets a maximum swipeable distance for each item.

    maxSwipeDistance :此道具为每个项目设置最大可滑动距离。
  • Finally, the renderItem prop takes a function that renders an item; this function will be passed an item prop that contains the data to be displayed.

    最后, renderItem接受一个渲染项目的函数。 此功能将被传递的item包含要显示的数据支撑。

Let’s update the home.js file to include the new UserList. Open the /src/home.js file and update it with the following:

让我们更新home.js文件以包括新的UserList 。 打开/src/home.js文件,并使用以下内容进行更新:

import React from "react";
    import { ScrollView, StyleSheet, ActivityIndicator } from "react-native";
    import UserList from "./user-list";

    class Home extends React.Component {
      state = {
        users: [],
        loading: true
      };
     ...
      render() {
        return (
          <ScrollView noSpacer={true} noScroll={true} style={styles.container}>
            {this.state.loading ? (
              <ActivityIndicator
                style={[styles.centering]}
                color="#ff8179"
                size="large"
              />
            ) : (
              <UserList users={this.state.users} />
            )}
          </ScrollView>
        );
      }
    }

    const styles = StyleSheet.create({
      ...
    });
    export default Home;

Now if you visit http://localhost:3000 on your browser, you should see a list of users, similar to the screenshot below:

现在,如果您在浏览器上访问http:// localhost:3000 ,应该会看到一个用户列表,类似于以下屏幕截图:

If you can’t see users listed, go through the tutorial again to see what you’ve have missed along the way.

如果看不到列出的用户,请再次阅读本教程,以了解您在此过程中错过了什么。

We’re using a SwipeableFlatList component which means each user item is swipeable, so let’s add actions that you can swipe to reveal. What’s the need of a SwipeableFlatList if it doesn’t reveal anything.

我们正在使用SwipeableFlatList组件,这意味着每个用户项目都是可滑动的,因此让我们添加可以滑动显示的操作。 如果不显示任何内容,则需要SwipeableFlatList。

向项目添加动作 ( Adding actions to item )

Each item within the list will be provided a set of actions that will be revealed when swiped to the left. The actions set will use the TouchableHighlight component encompassed by the View component. The TouchableHighlight component is used when we require viewers to respond to touches, more or less acting like a button. Create a file named user-actions.js in the src/ folder. Open the file and copy the following contents into it:

列表中的每个项目都将提供一组动作,向左滑动即可显示这些动作。 动作集将使用View组件包含的TouchableHighlight组件。 当我们要求观众响应触摸(或多或少像按钮一样)时,可以使用TouchableHighlight组件。 在src/文件夹中创建一个名为user-actions.js的文件。 打开文件并将以下内容复制到其中:

import React from "react";
    import {
      View,
      TouchableHighlight,
      Text,
      Alert,
      StyleSheet
    } from "react-native";

    const styles = StyleSheet.create({
      actionsContainer: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "flex-end",
        alignItems: "center",
        padding: 10
      },
      actionButton: {
        padding: 10,
        color: "white",
        borderRadius: 6,
        width: 80,
        backgroundColor: "#808080",
        marginRight: 5,
        marginLeft: 5
      },
      actionButtonDestructive: {
        backgroundColor: "#ff4b21"
      },
      actionButtonText: {
        textAlign: "center"
      }
    });

    const UserActions = () => {
      return (
        <View style={styles.actionsContainer}>
          <TouchableHighlight
            style={styles.actionButton}
            onPress={() => {
              Alert.alert("Tips", "You could do something with this edit action!");
            }}
          >
            <Text style={styles.actionButtonText}>Edit</Text>
          </TouchableHighlight>
          <TouchableHighlight
            style={[styles.actionButton, styles.actionButtonDestructive]}
            onPress={() => {
              Alert.alert(
                "Tips",
                "You could do something with this remove action!"
              );
            }}
          >
            <Text style={styles.actionButtonText}>Remove</Text>
          </TouchableHighlight>
        </View>
      );
    };

    export default UserActions;

The TouchableHighlight component takes an onPress callback that is triggered when the component is clicked. Each callback triggers an Alert display. Styles are also applied to the encompassing View component and other components on the page.

TouchableHighlight组件接受一个onPress回调,该回调在单击该组件时触发。 每个回调都会触发Alert显示。 样式也适用于页面上包含的View组件和其他组件。

To include the actions on each user item, update the UserList component to include the renderQuickActions prop, which also takes a function.

要包括对每个用户项目的操作,请更新UserList组件以包括renderQuickActions ,该renderQuickActions也具有一个功能。

import React from "react";
    ...
    import UserActions from "./user-actions";

    const UserList = ({ users }) => {
      return (
        <SwipeableFlatList
          ...
          renderQuickActions={UserActions}
        />
      );
    };

    export default UserList;

Now when you swipe left on any user item it reveals two actions. It should be similar to the screenshot below:

现在,当您向左滑动任何用户项目时,它将显示两个操作。 它应该类似于以下屏幕截图:

Actions revealed on swipe

标头组件 ( Header component )

Now that we’ve successfully fetched users and displayed them using native components, let’s liven the application by setting a header. Using the SafeAreaView component, we’ll create an area with defined boundaries. This will act as the header for our application. Create file called header.js and update it with the code below:

现在,我们已经成功获取用户并使用本机组件显示了他们,让我们通过设置标题来使应用程序更生动。 使用SafeAreaView组件,我们将创建一个具有定义边界的区域。 这将充当我们应用程序的标题。 创建名为header.js文件,并使用以下代码对其进行更新:

// src/header.js
    import React from 'react';
    import {SafeAreaView, View, Text, StyleSheet} from 'react-native';

    const Header = ({ onBack, title }) => (
      <SafeAreaView style={styles.headerContainer}>
        <View style={styles.header}>
          <View style={styles.headerCenter}>
            <Text accessibilityRole="heading" aria-level="3" style={styles.title}>{title}</Text>
          </View>
        </View>
      </SafeAreaView>
    );

    const styles = StyleSheet.create({
      headerContainer: {
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#ff4e3f',
        backgroundColor: '#ff8179',
      },
      header: {
        padding: 10,
        paddingVertical: 5,
        alignItems: 'center',
        flexDirection: 'row',
        minHeight: 50
      },
      headerCenter: {
        flex: 1,
        order: 2
      },
      headerLeft: {
        order: 1,
        width: 80
      },
      headerRight: {
        order: 3,
        width: 80
      },
      title: {
        fontSize: 19,
        fontWeight: '600',
        textAlign: 'center',
        color: 'white'
      },
    });

    export default Header;

Now let’s add the Header component to the App component. This will display a simple header at the top of the application. Update the App.js file to include the Header component:

现在,将Header组件添加到App组件。 这将在应用程序顶部显示一个简单的标题。 更新App.js文件以包含Header组件:

import React from 'react';
    ...
    import Header from './header';

    class App extends React.Component {
      render() {
        return (
          <View style={styles.appContainer}>
            <Header title="Random People" />
            <Home />
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      ...
    });

    AppRegistry.registerComponent('App', () => App);

    export default App;

After the application refreshes the header will be added to the top of the application.

应用程序刷新后,标题将添加到应用程序的顶部。

View after adding the header

Looks great, doesn’t it? It won’t be winning any awards, but it might win a lot of prospective react-native-web users. We’ve been able to achieve a lot of functionality after writing minimal code.

看起来不错,不是吗? 它不会获得任何奖项,但它可能会赢得很多潜在的“React本地”网络用户。 编写最少的代码后,我们已经能够实现很多功能。

Let’s see the various methods we can use to test the application on mobile.

让我们看看我们可以用来在移动设备上测试应用程序的各种方法。

在手机上测试 ( Testing on mobile )

To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application, this URL can be visited on your mobile browser to test the application.

为了在移动设备上测试应用程序,expo-cli提供了各种方法来测试移动应用程序。 第一种是使用运行应用程序后生成的URL,可以在您的移动浏览器上访问该URL来测试应用程序。

To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application. This URL can be visited on your mobile browser to test the application.

为了在移动设备上测试应用程序,expo-cli提供了各种方法来测试移动应用程序。 第一种是使用运行应用程序后生成的URL。 可以在您的移动浏览器上访问该URL以测试该应用程序。

Run the npm run start-native command within your project folder to run the application using expo. Expo typically starts your application on port 19002, so visit http://localhost:19002 to view the expo dev tools. Within the dev tools you can send a link as an SMS or email to your mobile phone.

在项目文件夹中运行npm run start-native命令,以使用expo运行该应用程序。 Expo通常在端口19002上启动您的应用程序,因此请访问http:// localhost:19002以查看expo dev工具。 在开发工具中,您可以将链接作为SMS或电子邮件发送到您的手机。

You can select any of the three connection options — an external tunnel, LAN or Local connection. For the local connection, your mobile phone and work PC have to be connected to the same network, but the tunnel works regardless.

您可以选择三个连接选项中的任何一个-外部隧道,LAN或本地连接。 对于本地连接,您的手机和工作PC必须连接到同一网络,但是无论如何隧道都可以工作。

The next option for testing on a mobile device is using a emulator. Using Android studio or Xcode, you can boot emulators for their respective platforms. Download and install the tool for the platform of choice — Xcode for iOS or Android studio for Android. After installation, run npm run android or npm run ios to start the application on any of the emulators.

在移动设备上进行测试的下一个选项是使用仿真器。 使用Android studioXcode ,您可以为各自的平台启动仿真器。 下载并安装用于所选平台的工具-适用于iOS的Xcode或适用于Android的Android studio。 安装后,运行npm run androidnpm run ios在任何仿真器上启动应用程序。

部署应用程序 ( Deploying the application )

We’ll be deploying our application to the Android Play store. To achieve this, we’ll need to update the app.json to include Android specific properties. Open the app.json file and update the file to include the android field:

我们将把应用程序部署到Android Play商店。 为此,我们需要更新app.json以包含Android特定的属性。 打开app.json文件并更新文件,使其包含android字段:

{
      "expo": {
        "sdkVersion": "31.0.0",
        "name": "random-people",
        "slug": "random-people",
        "version": "0.1.0",
        "description": "An application for displaying random people",
        "primaryColor": "#ff8179",
        "android": {
          "package": "com.random.people"
        }
      }
    }

The android.package field is a unique value that will represent your package in the app store. You can read more on the package-naming convention here. After updating the file, run the npm run build:android command.

android.package字段是一个唯一值,它将代表您在应用商店中的包。 您可以在此处阅读有关包命名约定的更多信息 。 更新文件后,运行npm run build:android命令。

This command will present you with a prompt, asking you to provide a keystore or to generate a new one. If you have an existing keystore, you can select this option or let expo generate one for your application.

此命令将提示您,要求您提供密钥库或生成一个新的密钥库 。 如果您已有密钥库,则可以选择此选项,或者让expo为您的应用程序生成一个。

Prompt to generate keystore.

After completion, a download link will be generated for your application. Clicking on this link will trigger a download for your APK.

完成后,将为您的应用程序生成一个下载链接。 点击此链接将触发您的APK下载。

To deploy the downloaded APKto the Android Play Store, visit the Play Console to create an account. After creating an account, you’ll be required to pay a registration fee of $25 before proceeding. After completing the registration process, visit this page and follow the steps to upload your application to the Play Store.

要将下载的APK部署到Android Play商店,请访问Play控制台创建一个帐户。 创建帐户后,您需要支付25美元的注册费才能继续操作。 完成注册过程后,请访问此页面并按照步骤将您的应用程序上传到Play商店。

摘要 ( Summary )

Using the React Native Web and React Native libraries, we’ve been able to create an application that can be deployed on several platforms using native components. Building multi-platform applications has never been easier. You can view the source code for the demo here.

使用React Native Web和React Native库,我们已经能够创建一个可以使用本机组件部署在多个平台上的应用程序。 构建多平台应用程序从未如此简单。 您可以在此处查看演示的源代码。

翻译自: https://scotch.io/tutorials/build-mobile-friendly-web-apps-with-react-native-web

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值