Skip to content

React Native API 调用 ​

React Native 提供了丰富的 API 接口,包括内置 API 和第三方库。本文将介绍如何在 React Native 中调用各种 API。

内置 API ​

1. 核心 API ​

1.1 平台特定 API ​

React Native 提供了 Platform API 来检测当前运行的平台:

jsx
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Platform.OS === 'ios' ? '#fff' : '#f0f0f0',
  },
  text: {
    fontSize: Platform.OS === 'ios' ? 16 : 14,
  },
});

1.2 设备信息 API ​

使用 Dimensions API 获取设备屏幕尺寸:

jsx
import { Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');
console.log(`Screen width: ${width}, height: ${height}`);

1.3 动画 API ​

React Native 提供了 Animated API 来创建流畅的动画:

jsx
import React, { useRef, useEffect } from 'react';
import { Animated, View, StyleSheet } from 'react-native';

const FadeInView = ({ children }) => {
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, [fadeAnim]);

  return (
    <Animated.View style={[styles.container, { opacity: fadeAnim }]}>
      {children}
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    backgroundColor: '#007AFF',
  },
});

2. 设备功能 API ​

2.1 相机 API ​

使用 react-native-camera 库访问设备相机:

jsx
import { RNCamera } from 'react-native-camera';

const CameraScreen = () => {
  return (
    <RNCamera
      style={styles.preview}
      type={RNCamera.Constants.Type.back}
      flashMode={RNCamera.Constants.FlashMode.on}
    >
      <View style={styles.buttonContainer}>
        <TouchableOpacity onPress={this.takePicture} style={styles.capture}>
          <Text style={styles.captureText}>拍摄</Text>
        </TouchableOpacity>
      </View>
    </RNCamera>
  );
};

2.2 位置 API ​

使用 react-native-geolocation-service 获取设备位置:

jsx
import Geolocation from 'react-native-geolocation-service';

const getLocation = () => {
  Geolocation.getCurrentPosition(
    (position) => {
      console.log(position);
    },
    (error) => {
      console.log(error.code, error.message);
    },
    {
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 10000,
    }
  );
};

2.3 存储 API ​

使用 AsyncStorage 存储数据:

jsx
import AsyncStorage from '@react-native-async-storage/async-storage';

// 存储数据
const storeData = async (key, value) => {
  try {
    const jsonValue = JSON.stringify(value);
    await AsyncStorage.setItem(key, jsonValue);
  } catch (e) {
    console.error('存储失败', e);
  }
};

// 读取数据
const getData = async (key) => {
  try {
    const jsonValue = await AsyncStorage.getItem(key);
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch (e) {
    console.error('读取失败', e);
  }
};

网络请求 ​

1. 使用 Fetch API ​

React Native 内置了 fetch API,用于发送网络请求:

jsx
const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.error('网络请求失败', error);
  }
};

2. 使用 Axios ​

可以使用 axios 库来简化网络请求:

jsx
import axios from 'axios';

const fetchData = async () => {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    console.error('网络请求失败', error);
  }
};

// 发送 POST 请求
const postData = async (data) => {
  try {
    const response = await axios.post('https://api.example.com/data', data);
    console.log(response.data);
  } catch (error) {
    console.error('网络请求失败', error);
  }
};

3. 处理网络错误 ​

jsx
const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const json = await response.json();
    return json;
  } catch (error) {
    console.error('网络请求失败', error);
    // 处理错误,如显示错误提示
    return null;
  }
};

原生模块调用 ​

1. 调用原生模块 ​

React Native 允许通过 NativeModules 调用原生代码:

jsx
import { NativeModules } from 'react-native';

// 调用原生模块方法
const result = NativeModules.MyNativeModule.myMethod('参数');
console.log(result);

2. 创建原生模块 ​

iOS 原生模块 ​

  1. 创建一个继承自 RCTBridgeModule 的类
  2. 实现所需的方法
  3. 在 @implementation 中添加 RCT_EXPORT_MODULE() 宏
  4. 使用 RCT_EXPORT_METHOD() 宏导出方法

Android 原生模块 ​

  1. 创建一个继承自 ReactContextBaseJavaModule 的类
  2. 实现 getName() 方法返回模块名称
  3. 使用 @ReactMethod 注解标记要导出的方法
  4. 在 Package 类中注册模块

第三方 API 集成 ​

1. Firebase ​

集成 Firebase 进行身份验证、数据库和云存储:

jsx
import auth from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';

// 邮箱密码登录
const signInWithEmail = async (email, password) => {
  try {
    const userCredential = await auth().signInWithEmailAndPassword(email, password);
    console.log('登录成功', userCredential.user);
  } catch (error) {
    console.error('登录失败', error);
  }
};

// 存储数据到 Firestore
const storeData = async (collection, data) => {
  try {
    await firestore().collection(collection).add(data);
    console.log('数据存储成功');
  } catch (error) {
    console.error('数据存储失败', error);
  }
};

2. 地图 API ​

集成 Google Maps 或百度地图:

jsx
import MapView, { Marker } from 'react-native-maps';

const MapScreen = () => {
  return (
    <MapView
      style={styles.map}
      initialRegion={{
        latitude: 37.78825,
        longitude: -122.4324,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
    >
      <Marker
        coordinate={{ latitude: 37.78825, longitude: -122.4324 }}
        title="Marker Title"
        description="Marker Description"
      />
    </MapView>
  );
};

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

API 调用最佳实践 ​

  1. 错误处理:始终处理 API 调用可能出现的错误
  2. 请求状态管理:显示加载指示器,避免重复请求
  3. 缓存策略:对频繁访问的数据进行缓存
  4. 请求节流:对频繁触发的请求进行节流处理
  5. 安全性:保护 API 密钥,使用 HTTPS,避免在客户端存储敏感信息
  6. 性能优化:使用适当的请求方法,减少不必要的数据传输

总结 ​

React Native 提供了丰富的 API 接口,从内置的核心 API 到第三方库,开发者可以根据需求选择合适的 API 来实现功能。通过合理的 API 调用和错误处理,可以构建出功能完善、性能优良的移动应用。

基于 VitePress 的本地知识库