React Native - 快速指南


React Native - 概述

为了更好地理解 React Native 概念,我们将从官方文档中借用几行内容 -

React Native 允许您仅使用 JavaScript 构建移动应用程序。它使用与 React 相同的设计,让您可以通过声明性组件构建丰富的移动 UI。使用 React Native,您不需要构建移动 Web 应用程序、HTML5 应用程序或混合应用程序;而是构建一个应用程序。您构建的真正的移动应用程序与使用 Objective-C 或 Java 构建的应用程序没有什么区别。React Native 使用与常规 iOS 和 Android 应用程序相同的基本 UI 构建块。您只需使用 JavaScript 和 React 将这些构建块组合在一起即可。

反应本机功能

以下是 React Native 的功能 -

  • React - 这是一个使用 JavaScript 构建 Web 和移动应用程序的框架。

  • Native - 您可以使用由 JavaScript 控制的本机组件。

  • 平台- React Native 支持 IOS 和 Android 平台。

React Native 的优势

以下是 React Native 的优点 -

  • JavaScript - 您可以使用现有的 JavaScript 知识来构建本机移动应用程序。

  • 代码共享- 您可以在不同平台上共享大部分代码。

  • 社区- 围绕 React 和 React Native 的社区很大,您将能够找到所需的任何答案。

反应本机限制

以下是 React Native 的限制 -

  • 本机组件- 如果您想创建尚未创建的本机功能,您将需要编写一些特定于平台的代码。

React Native - 环境设置

您需要安装一些东西来设置 React Native 的环境。我们将使用 OSX 作为我们的构建平台。

先生。 软件 描述
1 NodeJS 和 NPM 您可以按照我们的NodeJS 环境设置教程来安装 NodeJS。

第1步:安装create-react-native-app

在系统中成功安装 NodeJS 和 NPM 后,您可以继续安装 create-react-native-app (全局如下所示)。

C:\Users\Tutorialspoint> npm install -g create-react-native-app

第2步:创建项目

浏览所需的文件夹并创建一个新的 React Native 项目,如下所示。

C:\Users\Tutorialspoint>cd Desktop
C:\Users\Tutorialspoint\Desktop>create-react-native-app MyReactNative

执行上述命令后,将创建一个具有指定名称的文件夹,其中包含以下内容。

环境项目

第3步:NodeJS Python Jdk8

确保系统中安装了 Python NodeJS 和 jdk8,如果没有,请安装它们。除此之外,建议安装最新版本的纱线以避免某些问题。

第 4 步:安装 React Native CLI

您可以使用 install -g react-native-cli 命令在 npm 上安装 React Native 命令行界面,如下所示。

npm install -g react-native-cli

环境命令行

第 5 步:启动 React Native

要验证安装,请浏览项目文件夹并尝试使用启动命令启动项目。

C:\Users\Tutorialspoint\Desktop>cd MyReactNative
C:\Users\Tutorialspoint\Desktop\MyReactNative>npm start

如果一切顺利,您将获得如下所示的二维码。

环境包安装程序

按照说明,在 Android 设备上运行 React Native 应用程序的一种方法是使用 expo。在您的Android设备中安装expo客户端并扫描上面获得的二维码。

第 6 步:弹出项目

如果您想使用 android studio 运行 android 模拟器,请按ctrl+c退出当前命令行。

然后,执行运行弹出命令

npm run eject

这会提示您选择弹出选项,使用箭头选择第一个选项,然后按 Enter 键。

环境弹出命令

然后,您应该建议主屏幕上的应用程序名称以及 Android studio 和 Xcode 项目的项目名称。

环境弹出命令问题

尽管您的项目已成功弹出,但您可能会收到如下错误 -

环境弹出错误

忽略此错误并使用以下命令为 android 运行 React Native -

react-native run-android

但是,在此之前你需要安装 android studio。

第7步:安装Android Studio

访问网页https://developer.android.com/studio/并下载 android studio。

环境 Android Studio

下载它的安装文件后,双击它并继续安装。

环境 Android Studio3

步骤 8:配置 AVD 管理器

要配置 AVD 管理器,请单击菜单栏中的相应图标。

配置 AVD 管理器

步骤 9:配置 AVD 管理器

选择设备定义,建议使用Nexus 5X。

选择设备定义

单击“下一步”按钮,您将看到“系统映像”窗口。选择x86 图像选项卡。

系统镜像

然后,选择棉花糖并单击下一步。

选择系统镜像

最后点击Finish按钮完成AVD配置。

验证配置

配置虚拟设备后,单击操作列下的播放按钮来启动 Android 模拟器。

您的虚拟设备

第10步:运行android

打开命令提示符,浏览项目文件夹,然后执行react-native run-android命令。

运行安卓

然后,您的应用程序在另一个提示中开始执行,您可以看到其状态。

执行状态

在您的 Android 模拟器中,您可以看到默认应用程序的执行情况为 -

React Native 默认应用程序

第11步:local.properties

打开项目文件夹SampleReactNative/android中的android文件夹(在本例中)。创建名为local.properties的文件并在其中添加以下路径。

sdk.dir = /C:\\Users\\Tutorialspoint\\AppData\\Local\\Android\\Sdk

在这里,将Tutorialspoint替换为您的用户名。

第12步:热重载

要构建应用程序,请修改 App.js,所做的更改将在 Android 模拟器上自动更新。

如果没有,请单击 android 模拟器,然后按ctrl+m ,选择“启用热重载”选项。

环境热重载

React Native - 应用程序

如果您打开默认应用程序,您可以观察到 app.js 文件如下所示

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

export default class App extends React.Component {
   render() {
      return (
         <View style = {styles.container}>
            <Text>Open up App.js to start working on your app!</Text>
            <Text>Changes you make will automatically reload.</Text>
            <Text>Shake your phone to open the developer menu.</Text>
         </View>
      );
   }
}

const styles = StyleSheet.create({
   container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
   },
});

输出

开发应用程序

你好世界

要显示一条简单的消息“Welcome to Tutorialspoint”,请删除 CSS 部分并插入要打印的消息,该消息由 <view></view> 内的 <text></text> 标签包裹,如下所示。

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

export default class App extends React.Component {
   render() {
      return (
         <View>
            <Text>Welcome to Tutorialspoint</Text>
         </View>
      );
   }
}
你好世界

React Native - 状态

React Components 内部的数据由stateprops管理。在本章中,我们将讨论状态

状态和道具之间的区别

状态是可变的,而props不可变的。这意味着state可以在将来更新,而 props 则不能更新。

使用状态

这是我们的根组件。我们只是导入将在大多数章节中使用的Home 。

应用程序.js

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

export default class App extends React.Component {
   state = {
      myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
      nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
      fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
      culpa qui officia deserunt mollit anim id est laborum.'
   }
   render() {
      return (
      <View>
         <Text> {this.state.myState} </Text>
      </View>
      );
   }
}

我们可以在模拟器文本中看到状态,如下图所示。

反应本机状态

更新状态

由于状态是可变的,我们可以通过创建deleteState函数并使用onPress = {this.deleteText}事件调用它来更新它。

主页.js

import React, { Component } from 'react'
import { Text, View } from 'react-native'

class Home extends Component {
   state = {
      myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed 
         do eiusmod tempor incididunt ut labore et dolore magna aliqua.
         Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
         ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit 
         in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
         Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
         deserunt mollit anim id est laborum.'
   }
   updateState = () ⇒ this.setState({ myState: 'The state is updated' })
   render() {
      return (
         <View>
            <Text onPress = {this.updateState}>
               {this.state.myState}
            </Text>
         </View>
      );
   }
}
export default Home;

注意- 在所有章节中,我们将使用有状态(容器)组件的类语法和无状态(表示)组件的函数语法。我们将在下一章中了解有关组件的更多信息。

我们还将学习如何使用updateState的箭头函数语法。您应该记住,此语法使用词法范围,并且关键字将绑定到环境对象(类)。这有时会导致意外的Behave。

定义方法的另一种方法是使用 EC5 函数,但在这种情况下,我们需要在构造函数中手动绑定它。请考虑以下示例来理解这一点。

class Home extends Component {
   constructor() {
      super()
      this.updateState = this.updateState.bind(this)
   }
   updateState() {
      //
   }
   render() {
      //
   }
}

React Native - 道具

在上一章中,我们向您展示了如何使用可变状态。在本章中,我们将向您展示如何将 state 和props结合起来。

展示组件应该通过传递props来获取所有数据。只有容器组件才应该有状态

容器组件

我们现在将了解什么是容器组件以及它是如何工作的。

理论

现在我们将更新我们的容器组件。该组件将处理状态并将道具传递给演示组件。

容器组件仅用于处理状态。所有与视图相关的功能(样式等)都将在演示组件中处理。

例子

如果我们想使用上一章中的示例,我们需要从渲染函数中删除Text元素,因为该元素用于向用户呈现文本。这应该位于演示组件内。

让我们回顾一下下面给出的示例中的代码。我们将导入PresentationalComponent并将其传递给渲染函数。

当我们导入PresentationalComponent并将其传递给渲染函数后,我们需要传递props。我们将通过将myText = {this.state.myText}deleteText = {this.deleteText}添加到<PresentationalComponent>来传递道具。现在,我们将能够在演示组件内访问它。

应用程序.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'

export default class App extends React.Component {
   state = {
      myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
      nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
      aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
      nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
      officia deserunt mollit anim id est laborum.'
   }
   updateState = () => {
      this.setState({ myState: 'The state is updated' })
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState} updateState = {this.updateState}/>
         </View>
      );
   }
}

展示组件

我们现在将了解什么是演示组件以及它是如何工作的。

理论

展示组件应该仅用于向用户展示视图。这些组件没有状态。他们接收所有数据和函数作为道具。

最佳实践是使用尽可能多的演示组件。

例子

正如我们在上一章中提到的,我们将 EC6 函数语法用于表示组件。

我们的组件将接收 props,返回视图元素,使用{props.myText}呈现文本,并在用户单击文本时调用{props.deleteText}函数。

展示组件.js

import React, { Component } from 'react'
import { Text, View } from 'react-native'

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text onPress = {props.updateState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

现在,我们拥有与State章节中相同的功能。唯一的区别是我们将代码重构为容器和表示组件。

您可以运行该应用程序并查看文本,如以下屏幕截图所示。

React Native 属性

如果您单击文本,它将从屏幕上删除。

React Native Props 已更新

React Native - 样式

有几种方法可以在 React Native 中设置元素的样式。

您可以使用style属性来添加内联样式。然而,这不是最佳实践,因为它可能很难阅读代码。

在本章中,我们将使用样式表进行样式设置。

容器组件

在本节中,我们将简化上一章中的容器组件。

应用程序.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'

export default class App extends React.Component {
   state = {
      myState: 'This is my state'
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState}/>
         </View>
      );
   }
}

展示组件

在下面的示例中,我们将导入StyleSheet。在文件的底部,我们将创建样式表并将其分配给样式常量。请注意,我们的样式采用驼峰命名法,并且我们不使用px或 % 进行样式设置。

要将样式应用于文本,我们需要向Text元素添加style = {styles.myText}属性。

展示组件.js

import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text style = {styles.myState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

const styles = StyleSheet.create ({
   myState: {
      marginTop: 20,
      textAlign: 'center',
      color: 'blue',
      fontWeight: 'bold',
      fontSize: 20
   }
})

当我们运行该应用程序时,我们将收到以下输出。

React Native - Flexbox

为了适应不同的屏幕尺寸,React Native 提供了Flexbox支持。

我们将使用与React Native - 样式章节中使用的代码相同的代码。我们只会更改PresentationalComponent

布局

为了实现所需的布局,flexbox 提供了三个主要属性 - flexDirection justifyContentalignItems

下表显示了可能的选项。

财产 价值观 描述
弹性方向 ‘列’、‘行’ 用于指定元素是垂直对齐还是水平对齐。
调整内容 “中心”、“弹性开始”、“弹性结束”、“周围空间”、“空间之间” 用于确定元素应如何在容器内分布。
对齐项目 “中心”、“弯曲开始”、“弯曲结束”、“拉伸” 用于确定元素应如何沿辅助轴(与 flexDirection 相反)分布在容器内

如果你想垂直对齐项目并将它们居中,那么你可以使用以下代码。

应用程序.js

import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'

const Home = (props) => {
   return (
      <View style = {styles.container}>
         <View style = {styles.redbox} />
         <View style = {styles.bluebox} />
         <View style = {styles.blackbox} />
      </View>
   )
}

export default Home

const styles = StyleSheet.create ({
   container: {
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'grey',
      height: 600
   },
   redbox: {
      width: 100,
      height: 100,
      backgroundColor: 'red'
   },
   bluebox: {
      width: 100,
      height: 100,
      backgroundColor: 'blue'
   },
   blackbox: {
      width: 100,
      height: 100,
      backgroundColor: 'black'
   },
})

输出

React Native Flexbox 中心

如果需要将项目移到右侧,并且项目之间需要添加空格,那么我们可以使用以下代码。

应用程序.js

import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'

const App = (props) => {
   return (
      <View style = {styles.container}>
         <View style = {styles.redbox} />
         <View style = {styles.bluebox} />
         <View style = {styles.blackbox} />
      </View>
   )
}

export default App

const styles = StyleSheet.create ({
   container: {
      flexDirection: 'column',
      justifyContent: 'space-between',
      alignItems: 'flex-end',
      backgroundColor: 'grey',
      height: 600
   },
   redbox: {
      width: 100,
      height: 100,
      backgroundColor: 'red'
   },
   bluebox: {
      width: 100,
      height: 100,
      backgroundColor: 'blue'
   },
   blackbox: {
      width: 100,
      height: 100,
      backgroundColor: 'black'
   },
})

React Native Flexbox 正确

React Native - 列表视图

在本章中,我们将向您展示如何在 React Native 中创建列表。我们将在Home组件中导入List并将其显示在屏幕上。

应用程序.js

import React from 'react'
import List from './List.js'

const App = () => {
   return (
      <List />
   )
}
export default App

要创建列表,我们将使用map()方法。这将迭代一系列项目并渲染每个项目。

列表.js

import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'
   
class List extends Component {
   state = {
      names: [
         {
            id: 0,
            name: 'Ben',
         },
         {
            id: 1,
            name: 'Susan',
         },
         {
            id: 2,
            name: 'Robert',
         },
         {
            id: 3,
            name: 'Mary',
         }
      ]
   }
   alertItemName = (item) => {
      alert(item.name)
   }
   render() {
      return (
         <View>
            {
               this.state.names.map((item, index) => (
                  <TouchableOpacity
                     key = {item.id}
                     style = {styles.container}
                     onPress = {() => this.alertItemName(item)}>
                     <Text style = {styles.text}>
                        {item.name}
                     </Text>
                  </TouchableOpacity>
               ))
            }
         </View>
      )
   }
}
export default List

const styles = StyleSheet.create ({
   container: {
      padding: 10,
      marginTop: 3,
      backgroundColor: '#d9f9b1',
      alignItems: 'center',
   },
   text: {
      color: '#4f603c'
   }
})

当我们运行该应用程序时,我们将看到名称列表。

列表显示

您可以单击列表中的每个项目来触发带有名称的警报。

反应本机列表视图

React Native - 文本输入

在本章中,我们将向您展示如何在 React Native 中使用TextInput元素。

Home 组件将导入并呈现输入。

应用程序.js

import React from 'react';
import Inputs from './inputs.js'

const App = () => {
   return (
      <Inputs />
   )
}
export default App

输入

我们将定义初始状态。

定义初始状态后,我们将创建handleEmailhandlePassword函数。这些函数用于更新状态。

login ()函数只会提醒状态的当前值。

我们还将向文本输入添加一些其他属性,以禁用自动大写、删除 Android 设备上的底部边框并设置占位符。

输入.js

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'

class Inputs extends Component {
   state = {
      email: '',
      password: ''
   }
   handleEmail = (text) => {
      this.setState({ email: text })
   }
   handlePassword = (text) => {
      this.setState({ password: text })
   }
   login = (email, pass) => {
      alert('email: ' + email + ' password: ' + pass)
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Email"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleEmail}/>
            
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Password"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handlePassword}/>
            
            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.login(this.state.email, this.state.password)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})

每当我们在其中一个输入字段中输入内容时,状态就会更新。当我们单击“提交”按钮时,输入的文本将显示在对话框中。

反应本机文本输入

每当我们在其中一个输入字段中输入内容时,状态就会更新。当我们单击“提交”按钮时,输入的文本将显示在对话框中。

反应本机文本输入

React Native - 滚动视图

在本章中,我们将向您展示如何使用ScrollView元素。

我们将再次创建ScrollViewExample.js并将其导入Home

应用程序.js

import React from 'react';
import ScrollViewExample from './scroll_view.js';

const App = () => {
   return (
      <ScrollViewExample />
   )
}export default App

Scrollview 将呈现一个名称列表。我们将在状态中创建它。

滚动视图.js

import React, { Component } from 'react';
import { Text, Image, View, StyleSheet, ScrollView } from 'react-native';

class ScrollViewExample extends Component {
   state = {
      names: [
         {'name': 'Ben', 'id': 1},
         {'name': 'Susan', 'id': 2},
         {'name': 'Robert', 'id': 3},
         {'name': 'Mary', 'id': 4},
         {'name': 'Daniel', 'id': 5},
         {'name': 'Laura', 'id': 6},
         {'name': 'John', 'id': 7},
         {'name': 'Debra', 'id': 8},
         {'name': 'Aron', 'id': 9},
         {'name': 'Ann', 'id': 10},
         {'name': 'Steve', 'id': 11},
         {'name': 'Olivia', 'id': 12}
      ]
   }
   render() {
      return (
         <View>
            <ScrollView>
               {
                  this.state.names.map((item, index) => (
                     <View key = {item.id} style = {styles.item}>
                        <Text>{item.name}</Text>
                     </View>
                  ))
               }
            </ScrollView>
         </View>
      )
   }
}
export default ScrollViewExample

const styles = StyleSheet.create ({
   item: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      padding: 30,
      margin: 2,
      borderColor: '#2a4944',
      borderWidth: 1,
      backgroundColor: '#d2f7f1'
   }
})

当我们运行该应用程序时,我们将看到可滚动的名称列表。

React Native - 图像

在本章中,我们将了解如何在 React Native 中使用图像。

添加图像

让我们在src文件夹中创建一个新文件夹img。我们将在这个文件夹中添加我们的图像(myImage.png)。

我们将在主屏幕上显示图像。

应用程序.js

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

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

可以使用以下语法访问本地图像。

image_example.js

import React, { Component } from 'react'
import { Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {require('C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png')} />
)
export default ImagesExample

输出

反应本机图像

屏幕密度

React Native 提供了一种使用@2x、@3x后缀针对不同设备优化图像的方法。该应用程序将仅加载特定屏幕密度所需的图像。

以下是img文件夹中图像的名称。

my-image@2x.jpg
my-image@3x.jpg

网络图片

当使用网络图像时,我们需要source属性,而不是require。建议定义网络图像的宽度高度

应用程序.js

import React from 'react';
import ImagesExample from './image_example.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

image_example.js

import React, { Component } from 'react'
import { View, Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
   style = {{ width: 200, height: 200 }}
   />
)
export default ImagesExample

输出

网络图片

反应本机 - HTTP

在本章中,我们将向您展示如何使用fetch来处理网络请求。

应用程序.js

import React from 'react';
import HttpExample from './http_example.js'

const App = () => {
   return (
      <HttpExample />
   )
}
export default App

使用获取

一旦组件安装完毕,我们将使用componentDidMount生命周期方法从服务器加载数据。该函数将向服务器发送 GET 请求,返回 JSON 数据,将输出记录到控制台并更新我们的状态。

http_example.js

import React, { Component } from 'react'
import { View, Text } from 'react-native'

class HttpExample extends Component {
   state = {
      data: ''
   }
   componentDidMount = () => {
      fetch('https://jsonplaceholder.typicode.com/posts/1', {
         method: 'GET'
      })
      .then((response) => response.json())
      .then((responseJson) => {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) => {
         console.error(error);
      });
   }
   render() {
      return (
         <View>
            <Text>
               {this.state.data.body}
            </Text>
         </View>
      )
   }
}
export default HttpExample

输出

反应本机 HTTP

React Native - 按钮

在本章中,我们将向您展示 React Native 中的可触摸组件。我们称它们为“可触摸”,因为它们提供内置动画,我们可以使用onPress属性来处理触摸事件。

Facebook 提供了Button组件,它可以用作通用按钮。请考虑以下示例来理解这一点。

应用程序.js

import React, { Component } from 'react'
import { Button } from 'react-native'

const App = () => {
   const handlePress = () => false
   return (
      <Button
         onPress = {handlePress}
         title = "Red button!"
         color = "red"
      />
   )
}
export default App

如果默认的Button组件不能满足您的需求,您可以使用以下组件之一代替。

按钮 红色按钮

可触摸的不透明度

当触摸该元素时,该元素将改变元素的不透明度。

应用程序.js

import React from 'react'
import { TouchableOpacity, StyleSheet, View, Text } from 'react-native'

const App = () => {
   return (
      <View style = {styles.container}>
         <TouchableOpacity>
            <Text style = {styles.text}>
               Button
            </Text>
         </TouchableOpacity>
      </View>
   )
}
export default App

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
   },
   text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
   }
})

按钮 触摸不透明度

可触摸亮点

当用户按下该元素时,它会变暗,并且底层颜色将显示出来。

应用程序.js

import React from 'react'
import { View, TouchableHighlight, Text, StyleSheet } from 'react-native'

const App = (props) => {
   return (
      <View style = {styles.container}>
         <TouchableHighlight>
            <Text style = {styles.text}>
               Button
            </Text>
         </TouchableHighlight>
      </View>
   )
}
export default App

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
   },
   text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
   }
})

可触摸的原生反馈

这将在按下元素时模拟墨迹动画。

应用程序.js

import React from 'react'
import { View, TouchableNativeFeedback, Text, StyleSheet } from 'react-native'

const Home = (props) => {
   return (
      <View style = {styles.container}>
         <TouchableNativeFeedback>
            <Text style = {styles.text}>
               Button
            </Text>
         </TouchableNativeFeedback>
      </View>
   )
}
export default Home

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
   },
   text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
   }
})

无反馈可触摸

当你想要处理没有任何动画的触摸事件时应该使用这个组件。通常,这个组件使用得不多。

<TouchableWithoutFeedback>
   <Text>
      Button
   </Text>
</TouchableWithoutFeedback>

React Native - 动画

在本章中,我们将向您展示如何在 React Native 中使用LayoutAnimation

动画组件

我们将把myStyle设置为状态的一个属性。此属性用于为PresentationalAnimationComponent内的元素设置样式。

我们还将创建两个函数 - ExpandElementCollapseElement。这些函数将更新状态值。第一个将使用弹簧预设动画,而第二个将使用线性预设。我们也将把它们作为道具传递。Expand和Collapse按钮​​调用expandElement()和collapseElement ( )函数。

在此示例中,我们将动态更改框的宽度和高度。由于Home组件是相同的,我们将只更改Animations组件。

应用程序.js

import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'

class Animations extends Component {
   componentWillMount = () => {
      this.animatedWidth = new Animated.Value(50)
      this.animatedHeight = new Animated.Value(100)
   }
   animatedBox = () => {
      Animated.timing(this.animatedWidth, {
         toValue: 200,
         duration: 1000
      }).start()
      Animated.timing(this.animatedHeight, {
         toValue: 500,
         duration: 500
      }).start()
   }
   render() {
      const animatedStyle = { width: this.animatedWidth, height: this.animatedHeight }
      return (
         <TouchableOpacity style = {styles.container} onPress = {this.animatedBox}>
            <Animated.View style = {[styles.box, animatedStyle]}/>
         </TouchableOpacity>
      )
   }
}
export default Animations

const styles = StyleSheet.create({
   container: {
      justifyContent: 'center',
      alignItems: 'center'
   },
   box: {
      backgroundColor: 'blue',
      width: 50,
      height: 100
   }
})

React Native - 调试

React Native 提供了一些帮助调试代码的方法。

在应用程序开发者菜单中

您可以通过按command + D在 IOS 模拟器上打开开发者菜单。

在 Android 模拟器上,您需要按command + M

React Native 调试开发者菜单
  • 重新加载- 用于重新加载模拟器。您可以使用快捷键命令+ R

  • 远程调试 JS - 用于在浏览器开发人员控制台内激活调试。

  • 启用实时重新加载- 用于在保存代码时启用实时重新加载。调试器将在localhost:8081/debugger-ui打开。

  • Start Systrace - 用于启动基于 Android 标记的分析工具。

  • 显示检查器- 用于打开检查器,您可以在其中找到有关组件的信息。您可以使用快捷命令 + I

  • 显示性能监视器- 性能监视器用于跟踪应用程序的性能。

React Native - 路由器

在本章中,我们将了解 React Native 中的导航。

第1步:安装路由器

首先,我们需要安装Router。我们将在本章中使用 React Native Router Flux。您可以在终端中从项目文件夹运行以下命令。

npm i react-native-router-flux --save

第 2 步:整个申请

由于我们希望路由器处理整个应用程序,因此我们将其添加到index.ios.js中。对于 Android,您可以在index.android.js中执行相同的操作。

应用程序.js

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import Routes from './Routes.js'

class reactTutorialApp extends Component {
   render() {
      return (
         <Routes />
      )
   }
}
export default reactTutorialApp
AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)

第三步:添加路由器

现在我们将在 Components 文件夹中创建Routes组件。它将返回带有多个场景的Router。每个场景都需要key、c​​omponenttitle。Router 使用 key 属性在场景之间切换,组件将渲染在屏幕上,标题将显示在导航栏中。我们还可以将初始属性设置为最初要渲染的场景。

路由.js

import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'

const Routes = () => (
   <Router>
      <Scene key = "root">
         <Scene key = "home" component = {Home} title = "Home" initial = {true} />
         <Scene key = "about" component = {About} title = "About" />
      </Scene>
   </Router>
)
export default Routes

第 4 步:创建组件

我们已经有了前面章节中的Home组件;现在,我们需要添加“关于”组件。我们将添加goToAboutgoToHome函数来在场景之间切换。

主页.js

import React from 'react'
import { TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';

const Home = () => {
   const goToAbout = () => {
      Actions.about()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
         <Text>This is HOME!</Text>
      </TouchableOpacity>
   )
}
export default Home

关于.js

import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'

const About = () => {
   const goToHome = () => {
      Actions.home()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
         <Text>This is ABOUT</Text>
      </TouchableOpacity>
   )
}
export default About

该应用程序将呈现初始屏幕。

反应本机路由器

您可以按 按钮切换到关于屏幕。将出现后退箭头;您可以使用它返回到上一个屏幕。

反应本机路由器

React Native - 运行 IOS

如果您想在 IOS 模拟器中测试您的应用程序,您只需在终端中打开应用程序的根文件夹并运行 -

react-native run-ios

上面的命令将启动模拟器并运行应用程序。

我们还可以指定我们想要使用的设备。

react-native run-ios --simulator "iPhone 5s

在模拟器中打开应用程序后,您可以在 IOS 上按command + D打开开发人员菜单。您可以在我们的调试章节中查看更多相关信息。

您还可以通过按command + R重新加载 IOS 模拟器。

React Native - 运行 Android

我们可以通过在终端中运行以下代码来在Android平台上运行React Native应用程序。

react-native run-android

在 Android 设备上运行应用程序之前,您需要在开发人员选项中启用USB 调试

启用USB 调试后,您可以插入设备并运行上面给出的代码片段。

本机 Android 模拟器速度很慢。我们建议下载Genymotion来测试您的应用程序。

可以通过按command + M访问开发人员菜单。

React Native - 查看

View 是 React Native 中最常见的元素。您可以将其视为Web 开发中使用的div元素的等效项。

用例

现在让我们看看一些常见的用例。

  • 当您需要将元素包装在容器内时,可以使用View作为容器元素。

  • 当你想在父元素中嵌套更多元素时,父元素和子元素都可以是View。它可以有任意数量的孩子。

  • 当你想要设置不同元素的样式时,你可以将它们放置在View中,因为它支持style属性、flexbox等。

  • View还支持合成触摸事件,这可用于不同的目的。

我们已经在前面的章节中使用了View,并且我们也将在几乎所有后续章节中使用它。View可以被假定为 React Native中的默认元素。在下面给出的示例中,我们将嵌套两个视图和一个文本。

应用程序.js

import React, { Component } from 'react'
import { View, Text } from 'react-native'

const App = () => {
   return (
      <View>
         <View>
            <Text>This is my text</Text>
         </View>
      </View>
   )
}
export default App

输出

道具更新

React Native - WebView

在本章中,我们将学习如何使用WebView。当您想要将网页渲染到内联移动应用程序时,可以使用它。

使用网页视图

HomeContainer将是一个容器组件

应用程序.js

import React, { Component } from 'react'
import WebViewExample from './web_view_example.js'

const App = () => {
   return (
      <WebViewExample/>
   )
}
export default App;

让我们在src/components/home文件夹中创建一个名为WebViewExample.js的新文件。

web_view_example.js

import React, { Component } from 'react'
import { View, WebView, StyleSheet }

from 'react-native'
const WebViewExample = () => {
   return (
      <View style = {styles.container}>
         <WebView
         source = {{ uri:
         'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=tutorialspoint' }}
         />
      </View>
   )
}
export default WebViewExample;

const styles = StyleSheet.create({
   container: {
      height: 350,
   }
})

上述程序将生成以下输出。

反应本机 WebView

React Native - 模态

在本章中,我们将向您展示如何在 React Native 中使用模态组件。

现在让我们创建一个新文件:ModalExample.js

我们将把逻辑放在ModalExample中。我们可以通过运行toggleModal来更新初始状态。

通过运行toggleModal更新初始状态后,我们将把visible属性设置为我们的模态。当状态改变时,这个 prop 将会更新。

Android设备需要onRequestClose 。

应用程序.js

import React, { Component } from 'react'
import WebViewExample from './modal_example.js'

const Home = () => {
   return (
      <WebViewExample/>
   )
}
export default Home;

modal_example.js

import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet}

from 'react-native'
class ModalExample extends Component {
   state = {
      modalVisible: false,
   }
   toggleModal(visible) {
      this.setState({ modalVisible: visible });
   }
   render() {
      return (
         <View style = {styles.container}>
            <Modal animationType = {"slide"} transparent = {false}
               visible = {this.state.modalVisible}
               onRequestClose = {() => { console.log("Modal has been closed.") } }>
               
               <View style = {styles.modal}>
                  <Text style = {styles.text}>Modal is open!</Text>
                  
                  <TouchableHighlight onPress = {() => {
                     this.toggleModal(!this.state.modalVisible)}}>
                     
                     <Text style = {styles.text}>Close Modal</Text>
                  </TouchableHighlight>
               </View>
            </Modal>
            
            <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
               <Text style = {styles.text}>Open Modal</Text>
            </TouchableHighlight>
         </View>
      )
   }
}
export default ModalExample

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
      backgroundColor: '#ede3f2',
      padding: 100
   },
   modal: {
      flex: 1,
      alignItems: 'center',
      backgroundColor: '#f7021a',
      padding: 100
   },
   text: {
      color: '#3f2949',
      marginTop: 10
   }
})

我们的起始屏幕将如下所示 -

React Native 开放模态

如果我们单击该按钮,模式将打开。

反应本机模态

React Native - 活动指示器

在本章中,我们将向您展示如何在 React Native 中使用活动指示器。

第 1 步:应用程序

应用程序组件将用于导入并显示我们的ActivityIndi​​cator

应用程序.js

import React from 'react'
import ActivityIndicatorExample from './activity_indicator_example.js'

const Home = () => {
   return (
      <ActivityIndicatorExample />
   )
}
export default Home

第 2 步:ActivityIndi​​cator 示例

Animating 属性是一个布尔值,用于显示活动指示器。后者在组件安装后六秒关闭。这是使用closeActivityIndi​​cator()函数完成的。

Activity_indicator_example.js

import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from 'react-native';

class ActivityIndicatorExample extends Component {
   state = { animating: true }
   
   closeActivityIndicator = () => setTimeout(() => this.setState({
   animating: false }), 60000)
   
   componentDidMount = () => this.closeActivityIndicator()
   render() {
      const animating = this.state.animating
      return (
         <View style = {styles.container}>
            <ActivityIndicator
               animating = {animating}
               color = '#bc2b78'
               size = "large"
               style = {styles.activityIndicator}/>
         </View>
      )
   }
}
export default ActivityIndicatorExample

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: 70
   },
   activityIndicator: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      height: 80
   }
})

当我们运行应用程序时,我们将在屏幕上看到加载程序。六秒后它将消失。

React Native 活动指示器

React Native - 选择器

在本章中,我们将创建具有两个可用选项的简单选择器。

第 1 步:创建文件

在这里,App.js文件夹将用作演示组件。

应用程序.js

import React from 'react'
import PickerExample from './PickerExample.js'

const App = () => {
   return (
      <PickerExample />
   )
}
export default App

第二步:逻辑

this.state.user用于选择器控制。

当选择用户时将触发updateUser函数。

PickerExample.js

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'

class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
               <Picker.Item label = "Steve" value = "steve" />
               <Picker.Item label = "Ellen" value = "ellen" />
               <Picker.Item label = "Maria" value = "maria" />
            </Picker>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
   }
}
export default PickerExample

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

输出

反应本机选择器

如果您单击名称,它会提示您所有三个选项:

反应本机选择器

你可以选择其中之一,输出会像这样。

反应本机选择器

React Native - 状态栏

在本章中,我们将向您展示如何在 React Native 中控制状态栏的外观。

状态栏易于使用,您只需设置属性即可更改它。

hide属性可用于隐藏状态栏。在我们的示例中,它设置为false。这是默认值。

barStyle可以具有三个值 – dark -content、light-contentdefault

该组件还有其他几个可以使用的属性。其中一些是 Android 或 IOS 特定的。您可以在官方文档中查看。

应用程序.js

import React, { Component } from 'react';
import { StatusBar } from 'react-native'

const App = () => {
   return (
      <StatusBar barStyle = "dark-content" hidden = {false} backgroundColor = "#00BCD4" translucent = {true}/>
   )
}
export default App

如果我们运行该应用程序,状态栏将可见,并且内容将呈深色。

输出

React Native 状态栏

React Native - 开关

在本章中,我们将通过几个步骤解释Switch组件。

第 1 步:创建文件

我们将使用HomeContainer组件来实现逻辑,但我们需要创建展示组件。

现在让我们创建一个新文件:SwitchExample.js

第二步:逻辑

我们将用于切换开关项目的状态和函数的值传递给SwitchExample组件。切换函数将用于更新状态。

应用程序.js

import React, { Component } from 'react'
import { View } from 'react-native'
import SwitchExample from './switch_example.js'

export default class HomeContainer extends Component {
   constructor() {
      super();
      this.state = {
         switch1Value: false,
      }
   }
   toggleSwitch1 = (value) => {
      this.setState({switch1Value: value})
      console.log('Switch 1 is: ' + value)
   }
   render() {
      return (
         <View>
            <SwitchExample
            toggleSwitch1 = {this.toggleSwitch1}
            switch1Value = {this.state.switch1Value}/>
         </View>
      );
   }
}

第三步:演示

Switch 组件需要两个 props。onValueChange属性在用户按下开关后触发我们的切换功能。value prop绑定到HomeContainer组件的状态。

switch_example.js

import React, { Component } from 'react'
import { View, Switch, StyleSheet }

from 'react-native'

export default SwitchExample = (props) => {
   return (
      <View style = {styles.container}>
         <Switch
         onValueChange = {props.toggleSwitch1}
         value = {props.switch1Value}/>
      </View>
   )
}
const styles = StyleSheet.create ({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 100
   }
})

如果我们按下开关,状态就会更新。您可以在控制台中检查值。

输出

反应本机开关

React Native - 文本

在本章中,我们将讨论React Native 中的Text组件。

该组件可以嵌套,并且可以从父组件继承到子组件的属性。这在很多方面都很有用。我们将向您展示首字母大写、单词或文本部分样式等的示例。

第 1 步:创建文件

我们要创建的文件是text_example.js

第2步:App.js

在此步骤中,我们将仅创建一个简单的容器。

应用程序.js

import React, { Component } from 'react'
import TextExample from './text_example.js'

const App = () => {
   return (
      <TextExample/>
   )
}
export default App

第三步:文字

在这一步中,我们将使用继承模式。styles.text将应用于所有文本组件。

您还可以注意到我们如何为文本的某些部分设置其他样式属性。重要的是要知道所有子元素都有传递给它们的父样式。

文本示例.js

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

const TextExample = () => {
   return (
      <View style = {styles.container}>
         <Text style = {styles.text}>
            <Text style = {styles.capitalLetter}>
               L
            </Text>
            
            <Text>
               orem ipsum dolor sit amet, sed do eiusmod.
            </Text>
            
            <Text>
               Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam,
               quis aliquip ex ea commodo consequat.
            </Text>
            
            <Text style = {styles.italicText}>
               Duis aute ir