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

news/2024/8/26 17:12:59

介绍 (Introduction)

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, like push notifications and background sync, among other features.

多年来,随着媒体查询的出现和服务人员的引入,构建移动友好的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.

React Native是Facebook开发的一种多平台解决方案,可让您使用JavaScript构建移动应用程序。 这些移动应用程序被认为是多平台的,因为它们只编写一次并部署在许多平台上,例如Android,iOS和Web。

In this tutorial you’ll build an application that displays user information from the [Random User API](https://randomuser.me/ using React Native components like ScrollView, Text and Image. The app will run both on the web and mobile using the React Native Web library, which lets you use React Native components and APIs in web applications.

在本教程中,您将构建一个应用程序,使用React Native组件(例如ScrollView,Text和Image)显示[Random User API]( https://randomuser.me/)中的用户信息。该应用程序将同时在网络和移动设备上运行使用React Native Web库,该库使您可以在Web应用程序中使用React Native组件和API。

先决条件 (Prerequisites)

To complete this tutorial, you’ll need:

要完成本教程,您需要:

  • A local development environment for Node.js. Follow How to Install Node.js and Create a Local Development Environment

    Node.js的本地开发环境。 遵循如何安装Node.js和创建本地开发环境

  • Some familiarity with JavaScript. You can look at the How To Code in JavaScript series to learn more.

    熟悉JavaScript。 您可以查看“ 如何使用JavaScript编码”系列以了解更多信息。

  • Familiarity with React. You can follow the official React tutorial here to get up to speed with React.

    熟悉React。 您可以在此处遵循官方的React教程来快速了解React。

步骤1 –建立专案 (Step 1 – Creating the Project)

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引导您的应用程序,请运行以下命令:

  • npx create-react-app random-people

    npx create-react-app随机人

Run the following command to install the project’s development dependencies. If you’re using Yarn, use this command:

运行以下命令以安装项目的开发依赖项。 如果您使用的是Yarn,请使用以下命令:

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

    纱线添加--dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo

If you’re using npm, use this command:

如果您使用npm ,请使用以下命令:

  • npm install --save-dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo

    npm 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 module by running the following command if you’re using Yarn:

如果使用的是Yarn,请通过运行以下命令来安装expo-cli模块:

  • yarn global add expo-cli

    全球纱线展

Or, if using npm, use this command:

或者,如果使用npm ,请使用以下命令:

  • npm i g expo-cli

    npm ig expo-cli

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

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

  • yarn add expo react-native react-native-web react-art

    纱线添加博览会React本机React本机网React艺术

Or, for npm:

或者,对于npm

  • npm i expo react-native react-native-web react-art

    npm 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 set up the configuration files. Create a file called .babelrc in the root of your project:

下载了运行和构建应用程序所需的软件包后,下一步是设置配置文件。 在项目的根目录中创建一个名为.babelrc的文件:

  • nano .bablerc

    纳米.bablerc

Add the following code to the file to configure the transpilers your project will use:

将以下代码添加到文件中,以配置项目将使用的编译器:

.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文件的选项。

  • nano app.json

    纳米app.json

In the file, add this code:

在文件中,添加以下代码:

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

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 your editor:

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

  • nano package.json

    纳米package.json

Modify the file so it looks like this:

修改文件,使其如下所示:

// 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以查看该应用程序。

第2步–创建Home组件 (Step 2 – Creating the 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.

我们的应用程序是一个简单的演示,它通过Random User API显示用户。 使用API​​,我们将通过React Native提供的某些组件显示返回用户的名称和头像。 在src/目录中,创建一个名为home.js的文件。

  • nano src/home.js

    纳米src / home.js

Add this code to the file to define the component:

将此代码添加到文件中以定义组件:

src/home.js
src / 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;

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:

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

src/home.js
src / 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

步骤3 –创建应用程序组件 (Step 3 – Creating the 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.

在项目的根目录中创建一个名为App.js的新文件。

  • nano App.js

    纳米App.js

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. Add this code to App.js in the root of your project:

该文件将类似于src/App.js文件。 根App.js文件将充当Expo的入口文件,并且src/App.js文件存在于Create React App构建中。 将此代码添加到项目根目录中的App.js中:

App.js
App.js
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应用程序的入口点。

Now open src/App.js in your editor and add the same code to that file.

现在,在编辑器中打开src/App.js并将相同的代码添加到该文件中。

Now move on to creating the User item.

现在继续创建用户项。

步骤4 –创建用户项目 (Step 4 – Creating the 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:

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

  • nano src/user-item.js

    纳米src / user-item.js

Add the following code to the file:

将以下代码添加到文件中:

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

步骤5 –创建用户列表 (Step 5 – Creating the 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 in the src directory:

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

  • nano src/user-list.js

    纳米src / user-list.js

Add this code to the file:

将此代码添加到文件中:

src/user-list.js
src / 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 :此道具为每个项目设置最大可滑动距离。

    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 src/home.js file to include the new UserList. Open the /src/home.js file and update it with the following:

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

src/home.js
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 will see a list of users.

现在,如果您在浏览器上访问http:// localhost:3000 ,您将看到用户列表。

We’re using a SwipeableFlatList component which means each user item is swipeable, so let’s add actions that you can swipe to reveal.

我们使用一个SwipeableFlatList组件,这意味着每个用户产品滑动式,让我们添加动作,你可以刷卡透露。

步骤6 –向项目添加操作 (Step 6 – Adding Actions to Items)

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.

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

  • nano src/user-actions.js

    纳米src / user-actions.js

Add the following contents to the file:

将以下内容添加到文件中:

src/user-actions.js
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. Open src/user-list.js and modify it:

要包括对每个用户项目的操作,请更新UserList组件以包括renderQuickActions ,该renderQuickActions也具有一个功能。 打开src/user-list.js并对其进行修改:

src/user-list.js
src / user-list.js
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.

现在,当您向左滑动任何用户项目时,它会显示两个操作。

步骤7 –添加标题组件 (Step 7 – Adding a 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 a new file called header.js in the src/ folder:

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

  • nano src/header.js

    纳米src / header.js

Add the following code to the file:

将以下代码添加到文件中:

src/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组件:

src/App.js
src / App.js
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.

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

Be sure to modify the App.js file in the root of your project with these changes as well, so it works with Expo when you test it.

确保也通过这些更改修改项目根目录中的App.js文件,以便在测试它时可以与Expo一起使用。

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

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

步骤8 –在手机上进行测试 (Step 8 –Testing on Mobile)

The expo-cliutility provides various method to test the application on mobile devices. 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 methods 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 following command within your project to run the application with Expo:

在项目中运行以下命令以通过Expo运行应用程序:

  • npm run start-native

    npm run start-native

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.

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 development computer have to be connected to the same network, but the tunnel works regardless.

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

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 studio或Xcode ,您可以启动各自平台的仿真器。 下载并安装用于所选平台的工具-适用于iOS的Xcode或适用于Android的Android studio。 安装后,运行npm run androidnpm run ios在任何仿真器上启动应用程序。

步骤9 –部署应用程序 (Step 9 – 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 file 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字段:

app.json
app.json
{
  "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为您的应用程序生成一个。

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商店。

结论 (Conclusion)

Using the React Native Web and React Native libraries, you created 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://www.digitalocean.com/community/tutorials/build-mobile-friendly-web-apps-with-react-native-web


http://www.niftyadmin.cn/n/3649407.html

相关文章

sql server和Navicat使用遇到错误解决办法

sql server忘记密码和用户名:http://www.cnblogs.com/xushining/p/3752667.html navicat连接失败:http://blog.csdn.net/lsd123/article/details/5548827

afinal框架(FinalAcitivity,FinalBitmap,FinalDb,FinalHttp 四大模块)

github下载地址&#xff1a;https://github.com/yangfuhai/afinal Afinal是一个android的ioc&#xff0c;orm框架&#xff0c;内置了四大模块功能&#xff1a;FinalAcitivity,FinalBitmap,FinalDb,FinalHttp。通过finalActivity&#xff0c;我们可以通过注解的方式进行绑定ui和…

[WiX]我的第一个WiX安装脚本

我的第一个WiX安装脚本 WiX的Wiki&#xff1a;WiX 代表 Windows Installer Xml (WiX) toolset 它是建立Windows Installer的XML toolset (MSI) 包裹从XML 文件。它支持开发商集成他们的发布过程建立MSI 和MSM 设定包裹的命令行环境。内部结构Wix 由四份组成: 蜡烛、光、Lit 和…

WordPress添加侧栏小工具-博客统计(网站统计)

WordPress侧边栏“博客统计”小工具的制作方法。首先要下载cztcms.zip文件&#xff0c;解压得到一个PHP文件。蓝奏云地址&#xff1a;▶ cztcms.zip 1、将这个PHP文件放到主题目录下。打开主题目录下的function.php&#xff0c;在最后一个 ?> 前插入以下代码&#xff1a; i…

every 和some_如何使用.every()和.some()操纵JavaScript数组

every 和some介绍 (Introduction) ES5 and ES6 brought many changes to JavaScript, including better ways of working with a collection of data expressed as arrays. While the language has significantly improved support for declarative data manipulation on array…

PhotoView的使用

1. 功能介绍 特性(Features)&#xff1a; 支持Pinch手势自由缩放。支持双击放大/还原。支持平滑滚动。在滑动父控件下能够运行良好。&#xff08;例如&#xff1a;ViewPager&#xff09;支持基于Matrix变化&#xff08;放大/缩小/移动&#xff09;的事件监听。 优势&#xff1…

PackageManagerService概述

PackageManagerService主要负责对系统的apk进行管理&#xff0c;不管是系统apk(/system/app)&#xff0c;还是我们手工安装上去的&#xff0c;系统所有的apk都是由其管理的。 我们看一下PackageManager类图 从图可知&#xff0c;PackageManage负责提供对外的接口&#xff0c;Pa…

PHP+MySQL实现精确统计网站访问量(IP个数)

基于WordPress的网站有很多统计功能。但是只能统计文章阅读数。不能统计访客人数。以下代码可以实现获取来访用户的IP地址&#xff0c;一个IP对应一次访问。即使刷新也不会增加访问量。这个非常精确。 1、创建一个存储数据的表。进入MySQL后直接创建即可。 create table wp_jc_…