React Native

####搭建开发环境

  • 完整原生环境

  • 简易沙盒环境

必须安装的依赖有:

Node、Python2、JDK 和 Android Studio。</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">

虽然你可以使用任何编辑器来开发应用(编写 js 代码),但你仍然必须安装 Android Studio 来获得编译 Android 应用所需的工具和环境。 ### Node, Python2, JDK

我们建议直接使用搜索引擎搜索下载 Node 、Python2 和Java SE Development Kit (JDK)

注意 Node 的版本应大于等于 12,Python 的版本必须为 2.x(不支持 3.x),而 JDK 的版本必须是 1.8(目前不支持 1.9 及更高版本)。安装完 Node 后建议设置 npm 镜像(淘宝源)以加速后面的过程(或使用科学上网工具)。

注意:不要使用 cnpm!cnpm 安装的模块路径比较奇怪,packager 不能正常识别!

# 使用nrm工具切换淘宝源
npx nrm use taobao

# 如果之后需要切换回官方源可使用
npx nrm use npm

```</block>  <block class="native windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">### [](https://reactnative.cn/docs/getting-started#yarn-1)Yarn

[Yarn](http://yarnpkg.com/)是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。

npm install -g yarn


安装完 yarn 之后就可以用 yarn 代替 npm 了,例如用`yarn`代替`npm install`命令,用`yarn add 某第三方库名`代替`npm install 某第三方库名`。</block>  <block class="native mac linux windows android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">### [](https://reactnative.cn/docs/getting-started#android-%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83)Android 开发环境

如果你之前没有接触过 Android 的开发环境,那么请做好心理准备,这一过程相当繁琐。请`万分仔细`地阅读下面的说明,严格对照文档进行配置操作。

> 译注:请注意!!!国内用户`必须必须必须`有稳定的翻墙工具,否则在下载、安装、配置过程中会不断遭遇链接超时或断开,无法进行开发工作。某些翻墙工具可能只提供浏览器的代理功能,或只针对特定网站代理等等,请自行研究配置或更换其他软件。总之如果报错中出现有网址,那么 99% 就是无法正常翻墙。</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">#### [](https://reactnative.cn/docs/getting-started#1-%E5%AE%89%E8%A3%85-android-studio)1\. 安装 Android Studio

[首先下载和安装 Android Studio](https://developer.android.com/studio/index.html),国内用户可能无法打开官方链接,请自行使用搜索引擎搜索可用的下载链接。安装界面中选择"Custom"选项,确保选中了以下几项:</block>  <block class="native mac windows android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">*   `Android SDK`
*   `Android SDK Platform`
*   `Performance (Intel ® HAXM)` ([AMD 处理器看这里](https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html))
*   `Android Virtual Device`</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">然后点击"Next"来安装选中的组件。

> 如果选择框是灰的,你也可以先跳过,稍后再来安装这些组件。

安装完成后,看到欢迎界面时,就可以进行下面的操作了。

#### [](https://reactnative.cn/docs/getting-started#2-%E5%AE%89%E8%A3%85-android-sdk)2\. 安装 Android SDK

Android Studio 默认会安装最新版本的 Android SDK。目前编译 React Native 应用需要的是`Android 9 (Pie)`版本的 SDK(注意 SDK 版本不等于终端系统版本,RN 目前支持 android4.1 以上设备)。你可以在 Android Studio 的 SDK Manager 中选择安装各版本的 SDK。

你可以在 Android Studio 的欢迎界面中找到 SDK Manager。点击"Configure",然后就能看到"SDK Manager"。</block>  <block class="native windows android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">![Android Studio Welcome](https://upload-images.jianshu.io/upload_images/20585621-f2866ea6f0b1648e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">> SDK Manager 还可以在 Android Studio 的"Preferences"菜单中找到。具体路径是**Appearance & Behavior** → **System Settings** → **Android SDK**。

在 SDK Manager 中选择"SDK Platforms"选项卡,然后在右下角勾选"Show Package Details"。展开`Android 9 (Pie)`选项,确保勾选了下面这些组件(重申你必须使用稳定的翻墙工具,否则可能都看不到这个界面):

*   `Android SDK Platform 28`
*   `Intel x86 Atom_64 System Image`(官方模拟器镜像文件,使用非官方模拟器不需要安装此组件)

然后点击"SDK Tools"选项卡,同样勾中右下角的"Show Package Details"。展开"Android SDK Build-Tools"选项,确保选中了 React Native 所必须的`28.0.3`版本。你可以同时安装多个其他版本。

最后点击"Apply"来下载和安装这些组件。

#### [](https://reactnative.cn/docs/getting-started#3-%E9%85%8D%E7%BD%AE-android_home-%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F)3\. 配置 ANDROID_HOME 环境变量

React Native 需要通过环境变量来了解你的 Android SDK 装在什么路径,从而正常进行编译。</block>  <block class="native windows android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">打开`控制面板` -> `系统和安全` -> `系统` -> `高级系统设置` -> `高级` -> `环境变量` -> `新建`,创建一个名为`ANDROID_HOME`的环境变量(系统或用户变量均可),指向你的 Android SDK 所在的目录(具体的路径可能和下图不一致,请自行确认):

![ANDROID_HOME Environment Variable](https://upload-images.jianshu.io/upload_images/20585621-ee18230179f17dd4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

SDK 默认是安装在下面的目录:

c:\Users\你的用户名\AppData\Local\Android\Sdk


你可以在 Android Studio 的"Preferences"菜单中查看 SDK 的真实路径,具体是**Appearance & Behavior** → **System Settings** → **Android SDK**。

你需要关闭现有的命令符提示窗口然后重新打开,这样新的环境变量才能生效。

#### [](https://reactnative.cn/docs/getting-started#4-%E6%8A%8A%E4%B8%80%E4%BA%9B%E5%B7%A5%E5%85%B7%E7%9B%AE%E5%BD%95%E6%B7%BB%E5%8A%A0%E5%88%B0%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F-path-%E4%B8%AD)4\. 把一些工具目录添加到环境变量 Path 中

打开`控制面板` -> `系统和安全` -> `系统` -> `高级系统设置` -> `高级` -> `环境变量`,选中**Path**变量,然后点击**编辑**。点击**新建**然后把这些工具目录路径添加进去:platform-tools、emulator、tools、tools/bin

%ANDROID_HOME%\platform-tools
%ANDROID_HOME%\emulator
%ANDROID_HOME%\tools
%ANDROID_HOME%\tools\bin


> 如果你之前全局安装过旧的`react-native-cli`命令行工具,请使用`npm uninstall -g react-native-cli`卸载掉它以避免一些冲突。

使用 React Native 内建的命令行工具来创建一个名为"AwesomeProject"的新项目。这个命令行工具不需要安装,可以直接用 node 自带的`npx`命令来使用(注意 init 命令默认会创建最新的版本):

> **注意**:请`不要`单独使用常见的关键字作为项目名(如 class, native, new, package 等等)。请`不要`使用与核心模块同名的项目名(如 react, react-native 等)。请`不要`在目录、文件名中使用中文、空格等特殊符号。

npx react-native init AwesomeProject


> 提示:你可以使用`--version`参数(注意是`两`个杠)创建指定版本的项目。例如`npx react-native init MyApp --version 0.44.3`。注意版本号必须精确到两个小数点。

**Windows 用户请注意,请不要在某些权限敏感的目录例如 System32 目录中 init 项目!会有各种权限限制导致不能运行!**

如果你是想把 React Native 集成到现有的原生项目中,则步骤完全不同,请参考[集成到现有原生应用](https://reactnative.cn/docs/integration-with-existing-apps)。</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">## [](https://reactnative.cn/docs/getting-started#%E5%87%86%E5%A4%87-android-%E8%AE%BE%E5%A4%87)准备 Android 设备

你需要准备一台 Android 设备来运行 React Native Android 应用。这里所指的设备既可以是真机,也可以是模拟器。后面我们所有的文档除非特别说明,并不区分真机或者模拟器。Android 官方提供了名为 Android Virtual Device(简称 AVD)的模拟器。此外还有很多第三方提供的模拟器如[Genymotion](https://www.genymotion.com/download)、BlueStack 等。一般来说官方模拟器免费、功能完整,但性能较差。第三方模拟器性能较好,但可能需要付费,或带有广告。

### [](https://reactnative.cn/docs/getting-started#%E4%BD%BF%E7%94%A8-android-%E7%9C%9F%E6%9C%BA)使用 Android 真机

你也可以使用 Android 真机来代替模拟器进行开发,只需用 usb 数据线连接到电脑,然后遵照[在设备上运行](https://reactnative.cn/docs/running-on-device)这篇文档的说明操作即可。

### [](https://reactnative.cn/docs/getting-started#%E4%BD%BF%E7%94%A8-android-%E6%A8%A1%E6%8B%9F%E5%99%A8)使用 Android 模拟器

你可以使用 Android Studio 打开项目下的"android"目录,然后可以使用"AVD Manager"来查看可用的虚拟设备,它的图标看起来像下面这样:

![Android Studio AVD Manager](https://upload-images.jianshu.io/upload_images/20585621-1de47eee5652bc50.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

如果你刚刚才安装 Android Studio,那么可能需要先[创建一个虚拟设备](https://developer.android.com/studio/run/managing-avds.html)。点击"Create Virtual Device...",然后选择所需的设备类型并点击"Next",然后选择**Pie** API Level 28 image.

> 译注:请不要轻易点击 Android Studio 中可能弹出的建议更新项目中某依赖项的建议,否则可能导致无法运行。</block>  <block class="native windows android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">> 如果你还没有安装 HAXM(Intel 虚拟硬件加速驱动),则先点击"Install HAXM"或是按这篇[文档说明](https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows)来进行安装。</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">然后点击"Next"和"Finish"来完成虚拟设备的创建。现在你应该可以点击虚拟设备旁的绿色三角按钮来启动它了,启动完后我们可以尝试运行应用。</block>  <block class="native mac windows linux android active" style="box-sizing: inherit; margin: 0px; padding: 0px; display: block;">## [](https://reactnative.cn/docs/getting-started#%E7%BC%96%E8%AF%91%E5%B9%B6%E8%BF%90%E8%A1%8C-react-native-%E5%BA%94%E7%94%A8-1)编译并运行 React Native 应用

确保你先运行了模拟器或者连接了真机,然后在你的项目目录中运行`yarn android`或者`yarn react-native run-android`:

cd AwesomeProject
yarn android

写一个最简单的Hello World

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

export default class HelloWorldApp extends Component {
  render() {
    return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Text>Hello, world!</Text>
        </View>
    );
  }
}

Props(属性)
大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props(属性)。
以常见的基础组件Image为例,在创建一个图片时,可以传入一个名为source的 prop 来指定要显示的图片的地址,以及使用名为style的 prop 来控制其尺寸。

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

export default class Bananas extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <Image source={pic} style={{width: 193, height: 110}} />
    );
  }
}

自定义的组件也可以使用props。通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。

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

class Greeting extends Component {
  render() {
    return (
      <View style={{alignItems: 'center', marginTop: 50}}>
        <Text>Hello {this.props.name}!</Text>
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}
State(状态)

我们使用两种数据来控制一个组件:propsstateprops是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。对于需要改变的数据,我们需要使用state

一般来说,你需要在class中声明一个state对象,然后在需要修改时调用setState方法。

假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop。而文字的显示或隐藏的状态(快速的显隐切换就产生了闪烁的效果)则是随着时间变化的,因此这一状态应该写到state中。

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

class Blink extends Component {
  // 声明state对象
  state = { isShowingText: true };
  
  componentDidMount() {
    // 每1000毫秒对showText状态做一次取反操作
    setInterval(() => {
      this.setState({
        isShowingText: !this.state.isShowingText
      });
    }, 1000);
  }

  render() {
    // 根据当前showText的值决定是否显示text内容
    if (!this.state.isShowingText) {
      return null;
    }

    return (
      <Text>{this.props.text}</Text>
    );
  }
}

export default class BlinkApp extends Component {
  render() {
    return (
      <View>
        <Blink text='I love to blink' />
        <Blink text='Yes blinking is so great' />
        <Blink text='Why did they ever take this out of HTML' />
        <Blink text='Look at me look at me look at me' />
      </View>
    );
  }
}

实际开发中,我们一般不会在定时器函数(setInterval、setTimeout 等)中来操作 state。典型的场景是在接收到服务器返回的新数据,或者在用户输入数据之后。你也可以使用一些“状态容器”比如Redux来统一管理数据流。

每次调用setState时,BlinkApp 都会重新执行 render 方法重新渲染。这里我们使用定时器来不停调用setState,于是组件就会随着时间变化不停地重新渲染。

State 的工作原理和 React.js 完全一致,所以对于处理 state 的一些更深入的细节,你可以参阅React.Component API

译注:提示一些初学者应该牢记的要点:

  • 一切界面变化都是状态state变化
  • state的修改必须通过setState()方法
    • this.state.likes = 100; // 这样的直接赋值修改无效!
    • setState 是一个 merge 合并操作,只修改指定属性,不影响其他属性
    • setState 是异步操作,修改不会马上生效

看到这里,你可能觉得我们的例子总是千篇一律的黑色文本,太特么无聊了。那么我们一起来学习一下样式吧。

####处理文本输入
TextInput是一个允许用户输入文本的基础组件。它有一个名为onChangeText的属性,此属性接受一个函数,而此函数会在文本变化时被调用。另外还有一个名为onSubmitEditing的属性,会在文本被提交后(用户按下软键盘上的提交键)调用。

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

export default function PizzaTranslator() {
  const [text, setText] = useState('');
  return (
    <View style={{padding: 10}}>
      <TextInput
        style={{height: 40}}
        placeholder="Type here to translate!"
        onChangeText={text => setText(text)}
        defaultValue={text}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {text.split(' ').map((word) => word && '🍕').join(' ')}
      </Text>
    </View>
  );

####处理触摸事件
移动应用上的用户交互基本靠“摸”。当然,“摸”也是有各种姿势的:在一个按钮上点击,在一个列表上滑动,或是在一个地图上缩放。React Native 提供了可以处理常见触摸手势(例如点击或滑动)的组件, 以及可用于识别更复杂的手势的完整的[手势响应系统](https://react## 显示一个简单的按钮

Button是一个简单的跨平台的按钮组件。下面是一个最简示例:

<Button
  onPress={() => {
    Alert.alert("你点击了按钮!");
  }}
  title="点我!"
/>

上面这段代码会在 iOS 上渲染一个蓝色的标签状按钮,在 Android 上则会渲染一个蓝色圆角矩形带白字的按钮。点击这个按钮会调用"onPress"函数,具体作用就是显示一个 alert 弹出框。你还可以指定"color"属性来修改按钮的颜色。

image

再试试下面这个使用Button的例子吧。你可以点击"Tap to Play"来预览真实效果。(下面会显示一个嵌在网页中的手机模拟器,国内用户可能打不开这个网页模拟器,或速度非常慢)。

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

export default class ButtonBasics extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
          />
        </View>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
            color="#841584"
          />
        </View>
        <View style={styles.alternativeLayoutButtonContainer}>
          <Button
            onPress={this._onPressButton}
            title="This looks great!"
          />
          <Button
            onPress={this._onPressButton}
            title="OK!"
            color="#841584"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20
  },
  alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
})

Touchable 系列组件

这个组件的样式是固定的。所以如果它的外观并不怎么搭配你的设计,那就需要使用TouchableOpacity或是TouchableNativeFeedback组件来定制自己所需要的按钮,视频教程如何制作一个按钮讲述了完整的过程。或者你也可以在 github.com 网站上搜索 ‘react native button’ 来看看社区其他人的作品。

具体使用哪种组件,取决于你希望给用户什么样的视觉反馈:

  • 一般来说,你可以使用TouchableHighlight来制作按钮或者链接。注意此组件的背景会在用户手指按下时变暗。

  • 在 Android 上还可以使用TouchableNativeFeedback,它会在用户手指按下时形成类似墨水涟漪的视觉效果。

  • TouchableOpacity会在用户手指按下时降低按钮的透明度,而不会改变背景的颜色。

  • 如果你想在处理点击事件的同时不显示任何视觉反馈,则需要使用TouchableWithoutFeedback

某些场景中你可能需要检测用户是否进行了长按操作。可以在上面列出的任意组件中使用onLongPress属性来实现。

我们来看一下示例:

import React, { Component } from 'react';
import { Alert, Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';

export default class Touchables extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  _onLongPressButton() {
    Alert.alert('You long-pressed the button!')
  }


  render() {
    return (
      <View style={styles.container}>
        <TouchableHighlight onPress={this._onPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableHighlight</Text>
          </View>
        </TouchableHighlight>
        <TouchableOpacity onPress={this._onPressButton}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableOpacity</Text>
          </View>
        </TouchableOpacity>
        <TouchableNativeFeedback
            onPress={this._onPressButton}
            background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableNativeFeedback</Text>
          </View>
        </TouchableNativeFeedback>
        <TouchableWithoutFeedback
            onPress={this._onPressButton}
            >
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
          </View>
        </TouchableWithoutFeedback>
        <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>Touchable with Long Press</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 60,
    alignItems: 'center'
  },
  button: {
    marginBottom: 30,
    width: 260,
    alignItems: 'center',
    backgroundColor: '#2196F3'
  },
  buttonText: {
    textAlign: 'center',
    padding: 20,
    color: 'white'
  }
})

####使用滚动视图
ScrollView是一个通用的可滚动的容器,你可以在其中放入多个组件和视图,而且这些组件并不需要是同类型的。ScrollView 不仅可以垂直滚动,还能水平滚动(通过horizontal属性来设置)。

下面的示例代码创建了一个垂直滚动的ScrollView,其中还混杂了图片和文字组件。

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

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}

ScrollView适合用来显示数量不多的滚动元素。放置在ScrollView中的所有组件都会被渲染,哪怕有些组件因为内容太长被挤出了屏幕外。如果你需要显示较长的滚动列表,那么应该使用功能差不多但性能更好的FlatList组件。
####使用长列表
React Native 提供了几个适用于展示长列表数据的组件,一般而言我们会选用FlatList或是SectionList

FlatList组件用于显示一个垂直的滚动列表,其中的元素之间结构近似而仅数据不同。

FlatList更适于长列表数据,且元素个数可以增删。和ScrollView不同的是,FlatList并不立即渲染所有元素,而是优先渲染屏幕上可见的元素。

FlatList组件必须的两个属性是datarenderItemdata是列表的数据源,而renderItem则从数据源中逐个解析数据,然后返回一个设定好格式的组件来渲染。

下面的例子创建了一个简单的FlatList,并预设了一些模拟数据。首先是初始化FlatList所需的data,其中的每一项(行)数据之后都在renderItem中被渲染成了Text组件,最后构成整个FlatList

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

export default class FlatListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Dan'},
            {key: 'Dominic'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

如果要渲染的是一组需要分组的数据,也许还带有分组标签的,那么SectionList将是个不错的选择

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

export default class SectionListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'D', data: ['Devin', 'Dan', 'Dominic']},
            {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  sectionHeader: {
    paddingTop: 2,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 2,
    fontSize: 14,
    fontWeight: 'bold',
    backgroundColor: 'rgba(247,247,247,1.0)',
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

列表的一个常用场景就是从服务器端取回列表数据然后显示,要实现这一过程,你可能还需要学习React Native 的网络相关用法.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值