如何使用React Native构建iOS应用

1,234 阅读5分钟

React对于创建大型应用程序来说非常简单和高效。React Native使你能够使用React来构建在Android和iOS上运行的移动应用。

在本教程中,我们将演示如何使用React Native构建iOS应用程序。

什么是React Native?

React Native使你能够使用JavaScript编写Android和iOS应用程序。它使用React的虚拟DOM概念来操作本地平台的UI组件,为用户提供熟悉的体验。

iOS应用只能在macOS上构建,所以我们将从演示如何在Mac上安装React Native开始我们的教程。

在macOS上安装React Native

React Native CLI是以npm包的形式提供的。在安装它之前,确保Xcode已经安装在你的系统上。这是你构建原生iOS代码供React Native使用的地方。从App Store上安装Xcode

一旦Xcode安装完毕,我们就可以开始构建我们的应用程序。我们将使用Cocoapods作为一个依赖管理器。使用brew install ruby 安装Ruby,然后使用sudo gem install cocoapods 将Cocoapods作为宝石安装。

npm i -g react-native-cli

使用react-native init myproject 创建一个新的React Native项目。

在你当前的工作目录下应该创建一个新的myproject 文件夹,结构如下。

├── App.js
├── __tests__
├── android
├── app.json
├── babel.config.js
├── index.js
├── ios
├── metro.config.js
├── node_modules
├── package.json
└── yarn.lock

通过运行npm run ios 来启动该项目。这将在iOS模拟器上启动该应用。

Welcome to React Native Screen

为iOS构建一个React Native应用程序

为iOS和Android构建React Native应用的过程是相似的,直到你开始处理平台特定的API。大多数可用的UI元素对Android和iOS平台都适用。

React Native提供了基本的积木式元素,用于构建复杂的UI。其中最重要的有。

  • Text 用于在应用程序中显示文本 - 例如。<Text>Some Text</Text>
  • View 是一个支持布局和样式的容器--例如。<View><Text>Some Text</Text></View>

你可以在React Native文档中找到按钮、列表、图像、样式、用户输入等核心组件和API的完整列表。

React Native应用程序的入口点是index.js 。它包含了渲染应用程序的主要组件。

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
// registering the component to be rendered.
AppRegistry.registerComponent(appName, () => App);

React Native组件

React Native组件与React组件非常相似。所有的React API在React Native中也都可用。

让我们创建一个简单的增量按钮来更好地理解React Native APIs。

import React, { useState } from 'react';

/* Import basic components from react native */
import {
  Button,
  SafeAreaView,
  StatusBar,
  View,
  Text
} from 'react-native';


const App = () => {
/* using useState Hook for creating state*/
  const [count,setCount]=useState(0);
  return (
   /* using state in button and updating on click*/
    <SafeAreaView>
      <StatusBar/>
      <View style={{marginTop:"100%"}}>
      {/* using state in button and updating on click*/}
        <Button onPress={()=>setCount(count+1)} title={`Count is ${count}`} />
      </View>
    </SafeAreaView>
  );
};

export default App;

所有的React Hooks都可以在React Native中使用。

Count Is 0 Screen

进行网络调用

与外部服务的通信对任何应用程序都非常重要。React Native提供了对平台API的统一抽象。这个例子展示了fetch 与React Native提供的Image ,非常有效。

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, SafeAreaView, Text, View, Image } from 'react-native';
export default App = () => {
  // state for loading
  const [isLoading, setLoading] = useState(true);
  // state to hold fetched data
  const [data, setData] = useState(null);
  // use effect to fire up on component load
  useEffect(() => {
    fetch('https://random.dog/woof.json')
      .then((response) => response.json())
      // set the data
      .then((json) => setData(json.url))
      // if error log the error
      .catch((error) => console.error(error))
      // stop loading(by setting the isLoading false)
      .finally(() => setLoading(false));
  }, []);
  return (
    <View style={{ flex: 1, padding: 24 }}>
      <SafeAreaView />
      {/*Check if */}
      {isLoading ? <ActivityIndicator /> : (
        data ? <Image
          style={{
            width: 350,
            height: 400
          }}
          source={{
            uri: data
          }}
        /> : <Text>No Image</Text>
      )}
      <Text>{data}</Text>
    </View>
  );
};

Dog Picture on Device

使用npm包

React Native有一个庞大的开发者社区,他们不断涌现出高质量的库来帮助完成各种任务。

为了演示如何在你的React Native iOS应用中集成第三方库,让我们使用一个流行的存储库为我们的应用添加缓存。react-native-mmkv-storage是用C++编写的。

由于react-native-mmkv-storage使用原生代码,安装过程与纯JavaScript模块略有不同。

首先,使用npm安装react-native-mmkv-storage

npm install react-native-mmkv-storage

接下来,通过改变部署目标来更新ios/Podfile

# PodFile
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
# changed from 10.0 to 11.0
platform :ios, '11.0'
// ...

现在使用pod install 命令在ios 目录中安装模块的本地部分。安装方式根据模块的不同而不同。

在代码中使用该库来存储从API返回的数据。

// App.js
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, SafeAreaView, Text, View } from 'react-native';
import { MMKV } from './storage';
export default App = () => {
  // state for loading
  const [isLoading, setLoading] = useState(true);
  // state to hold fetched data
  const [data, setData] = useState([]);
  // use effect to fire up on component load
  useEffect(() => {
    MMKV.getArrayAsync("data_val").then((cachedValue) => {
      if (cachedValue && cachedValue.length) {
        setData(cachedValue)
        return
      }
      fetch('https://api.github.com/users')
        .then((response) => response.json())
        // set the data
        .then(async (json) => {
          await MMKV.setArrayAsync("data_val", json)
          setData(json)
        })
        // if error log the error
        .catch((error) => console.error(error))
      // stop loading(by setting the isLoading false)
    }).finally(() => setLoading(false));
  }, [])
  return (
    <View style={{ flex: 1, padding: 24 }}>
      <SafeAreaView>
      </SafeAreaView>
      {/*Check if */}
      {isLoading ? <ActivityIndicator /> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.id} {item.login}</Text>
          )}
        />
      )}
    </View>
  );
};


// storage.js
import MMKVStorage from "react-native-mmkv-storage"
export const MMKV = new MMKVStorage.Loader().initialize();

List of Names on Screen

使用React Native提供的Native APIs

React Native提供了一个围绕一些本地API的薄包装JavaScript,包括ActionSheetIOSDynamicColorIOS 、和Settings

Settings 用于在设备上存储键值对。ActionSheetIOS 打开动作底单,并与iOS设备共享底单。DynamicColorIOS 用于根据设备主题(即深色或浅色主题)定义颜色。

下面这个来自React Native文档的例子使用了ActionSheetIOS 。这些API的使用就像使用正常的JavaScript对象或函数一样。

import React, { useState } from "react";
import { ActionSheetIOS, Button, StyleSheet, Text, View } from "react-native";

const App = () => {
  const [result, setResult] = useState("🔮");

  const onPress = () =>
 // open sheet
    ActionSheetIOS.showActionSheetWithOptions(
      {
        options: ["Cancel", "Generate number", "Reset"],
        destructiveButtonIndex: 2,
        cancelButtonIndex: 0,
        userInterfaceStyle: 'dark'
      },
      buttonIndex => {
 // handle button press on the sheet
        if (buttonIndex === 0) {
          // cancel action
        } else if (buttonIndex === 1) {
          setResult(Math.floor(Math.random() * 100) + 1);
        } else if (buttonIndex === 2) {
          setResult("🔮");
        }
      }
    );

  return (
    <View style={styles.container}>
      <Text style={styles.result}>{result}</Text>
      <Button onPress={onPress} title="Show Action Sheet" />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center"
  },
  result: {
    fontSize: 64,
    textAlign: "center"
  }
});

export default App;

总结

使用React Native构建iOS应用是非常容易的。在本教程中,我们演示了如何使用React Native中的React概念安装React Native。我们涵盖了React Native开箱即用的基本组件,展示了如何安装库,并向你介绍了一些围绕React Native提供的本地API的封装器。

The postHow to build iOS apps using React Nativeappeared first onLogRocket Blog.