2-14~2-20 React Native 基础知识

227 阅读2分钟

什么是 React Native?

React Native 是一个使用 JavaScript 和 React 编写原生 iOS 和 Android 移动应用的框架。官方口号为“学习一次,到处编写”。与直接使用 JavaScript 编写的 H5 页面或混合应用不同,React Native 编写的应用是真正的原生应用,而不是运行在浏览器环境中的网页。

React Native 使用与原生应用相同的 UI 组件,因此最终渲染出来的也是原生组件,提升了性能。


如何编写 React Native 应用?

与编写 Web 应用不同,React Native 中不使用 divspan 等标签,而是使用 React Native 官方提供的组件,如 ViewText 等来构建页面。以下是一个简单的示例:

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

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

React Native 基础组件:ViewText

在 React Native 中,ViewText 可以类比为 HTML 中的 divspan。然而,与 CSS 中的元素继承属性不同,React Native 中的 Text 组件只能放置文本,不支持直接放置样式(如颜色、字体)在 View 内部。以下是正确的样式使用方式:

<View>
  <Text style={{ color: 'red' }}>一些文本</Text>
  <Text style={{ color: 'red' }}>一些文本</Text>
</View>

React Native 样式

React Native 使用 JavaScript 来定义样式,核心组件通过 style 属性接收样式。样式名称遵循 Web 上 CSS 的命名规则,但采用驼峰命名法(例如:background-color 改为 backgroundColor)。常见的样式方式如下:

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

const styles = StyleSheet.create({
  bigBlue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

布局与尺寸

React Native 使用 Flexbox 规则来布局组件,适应不同屏幕尺寸。布局使用 flexDirectionjustifyContentalignItems 等属性来控制。

Flexbox 布局

flexDirection

控制子元素的排列方向,默认为 column(垂直排列):

<View style={{ flexDirection: 'row' }}>
  <View style={{ width: 50, height: 50, backgroundColor: 'powderblue' }} />
  <View style={{ width: 50, height: 50, backgroundColor: 'skyblue' }} />
  <View style={{ width: 50, height: 50, backgroundColor: 'steelblue' }} />
</View>

justifyContent

控制子元素沿主轴的排列方式:

<View style={{
  flexDirection: 'column',
  justifyContent: 'space-between',
}}>
  <View style={{ width: 50, height: 50, backgroundColor: 'powderblue' }} />
  <View style={{ width: 50, height: 50, backgroundColor: 'skyblue' }} />
  <View style={{ width: 50, height: 50, backgroundColor: 'steelblue' }} />
</View>

alignItems

控制子元素在次轴(垂直方向)上的排列方式:

<View style={{ alignItems: 'center' }}>
  <Text>Align Center</Text>
</View>

flexWrap

控制当一条轴线排不下时,如何换行:

<View style={{ flexWrap: 'wrap' }}>
  <Text>Item 1</Text>
  <Text>Item 2</Text>
</View>

滚动视图

在 React Native 中,使用 ScrollViewFlatList 来实现滚动效果。ScrollView 用于显示少量滚动内容,而 FlatList 用于性能优化较好的长列表。

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

export default class ScrollDemo extends Component {
  render() {
    return (
      <ScrollView>
        <Text style={{ fontSize: 80 }}>React Native</Text>
        <Text style={{ fontSize: 80 }}>React Native</Text>
      </ScrollView>
    );
  }
}

FlatList 示例:

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

export default class FlatListDemo extends Component {
  render() {
    return (
      <FlatList
        data={[{ key: 'a' }, { key: 'b' }]}
        renderItem={({ item }) => <Text>{item.key}</Text>}
      />
    );
  }
}

React Native 触摸事件

React Native 提供了一系列的 Touchable 组件(如 TouchableOpacityTouchableNativeFeedbackTouchableHighlight 等)来处理触摸事件:

<TouchableOpacity onPress={this._onPressButton}>
  <Image style={styles.button} source={require('./myButton.png')} />
</TouchableOpacity>

常用触摸事件:

  • onPress: 触摸结束时调用。
  • onPressIn: 按下时调用。
  • onPressOut: 释放时调用。

网络请求

React Native 支持 fetch API,用于请求后台接口。以下是一个使用 fetch 请求数据的示例:

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
}