效果如上图所示,通过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;