React Native 结合 iOS 混合开发

请添加图片描述

效果如上图所示,通过IOS原生代码编写供 React Native 调用的接口,实现计算一个数的平方。举例比较简单,诣在展示 React Native 与 IOS 原生平台如何桥接。

1、在项目中新建 MyModule.h、MyModule.m 文件

File -> New -> File

请添加图片描述

请添加图片描述

2、MyModule.h

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
#import <React/RCTConvert.h>
#import <EventKit/EventKit.h>
#import <UIKit/UIKit.h>

@interface MyModule : NSObject <RCTBridgeModule>

@end

3、MyModule.m

#import "MyModule.h"

@implementation MyModule

RCT_EXPORT_MODULE()

// 常量,调用方式在 react native 中
- (NSDictionary *)constantsToExport {
  return @{
    @"hello": @"这是我编写的第一个 iOS 原生模块!",
    @"me": @"我是谁?"
  };
}
// 导出的方法,调用方式在 react native 中
RCT_EXPORT_METHOD(addEventMoreTwo:(NSString *)name location:(NSString *)location date:(NSString *)ISO8601DateString)
{
  NSDate *date = [RCTConvert NSDate:ISO8601DateString];
  NSLog(@"Pretending to create an event %@ at %@ at %@", name, location, date);
  RCTLogInfo(@"Pretending to create an event %@ at %@ at %@", name, location, date);
}
// 同上
RCT_EXPORT_METHOD(squareMe:(NSString *)number:(RCTResponseSenderBlock)callback) {
  int num = [number intValue];
  callback(@[[NSNull null], [NSNumber numberWithInt:(num*num)]]);
}


@end

4、RN

import React, {useState} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Alert,
  TextInput,
} from 'react-native';

import {NativeModules} from 'react-native';
const MyModule = NativeModules.MyModule;

const App = () => {
  let [num, setNumber] = useState(0);

  const squareMe = num => {
    if (num === '') return;
    MyModule.squareMe(num, (err, num) => {
      if (err) {
        Alert.alert(err);
      } else {
        setNumber(num);
      }
    });
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.text}>{MyModule.hello}</Text>
      <TextInput style={styles.textInput} onChangeText={num => squareMe(num)} />
      <Text style={styles.text}>{num}</Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textInput: {
    width: 100,
    borderColor: 'black',
    borderWidth: 1
  },
  text: {
    fontSize: 20,
    fontWeight: 'bold',
    margin: 20,
  }
});

export default App;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易山易酒易诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值