react-native之RN跳转原生界面

混合开发中不可避免的会遇到原生页面与非原生页面之间的跳转, 这篇文章记录一下 RN 页面跳转原生页面的一些具体操作.

1.配置原生文件

AppDelegate.h 文件中声明一个属性 nav:

1
2

@property (nonatomic, strong) UINavigationController * nav;

AppDelegate.m 文件中配置导航栏:

1
2
3
4
5
6
7

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
_nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.window.rootViewController = _nav;
[self.window makeKeyAndVisible];

2.创建文件实现RCTBridgeModule协议

创建一个继承 NSObject 的类:

1
2
3
4
5
6
7
8
9
10
11
12
13

//.h文件

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

NS_ASSUME_NONNULL_BEGIN

@interface RNToNative : NSObject<RCTBridgeModule>

@end

NS_ASSUME_NONNULL_END
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//.m文件

#import "RNToNative.h"
#import <React/RCTBridge.h>
#import "NativeViewController.h"
#import "AppDelegate.h"

@implementation RNToNative

RCT_EXPORT_MODULE(RNToNative);

//无参
RCT_EXPORT_METHOD(jumpToNative) {

dispatch_async(dispatch_get_main_queue(), ^{

NativeViewController *vc = [[NativeViewController alloc] init];
AppDelegate *app = (AppDelegate *)UIApplication.sharedApplication.delegate;
[app.nav pushViewController:vc animated:YES];
});
}

//有参
RCT_EXPORT_METHOD(jump2Native:(NSString *)para) {
dispatch_async(dispatch_get_main_queue(), ^{

NativeViewController *vc = [[NativeViewController alloc] init];
vc.para = para;
AppDelegate *app = (AppDelegate *)UIApplication.sharedApplication.delegate;
[app.nav pushViewController:vc animated:YES];
});
}

@end

3.在 RN 文件中配置

直接贴源码好了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//RNToNative为在原生文件中定义的类名称.
jumpToNative(){
var jump = NativeModules.RNToNative;
InteractionManager.runAfterInteractions(() => {

//jumpToNative为在原生文件中定义的函数名称, 此为无参的函数
jump.jumpToNative();
})
};
jumpToNativeWithPara() {
var jump = NativeModules.RNToNative;
InteractionManager.runAfterInteractions(() => {

//jump2Native为在原生文件中定义的函数名称, 此为带参的函数
jump.jump2Native("hello");
})
}

render() {
return (
<View style={{flex: 1,justifyContent: 'space-around'}}>
<TouchableOpacity activeOpacity={0.5} onPress={this.jumpToNative} style={styles.btn}>
<Text>跳转原生(无参数)</Text>
</TouchableOpacity>

<TouchableOpacity activeOpacity={0.5} onPress={this.jumpToNativeWithPara} style={styles.btn}>
<Text>跳转原生(带参数)</Text>
</TouchableOpacity>
</View>

)
}

效果如下:
rn跳转原生

-------------本文结束感谢您的阅读-------------
分享使我快乐!